The ESP32 Web Relay is a simple yet effective device for controlling a single relay switch via a web interface. It's built using an ESP32 microcontroller and allows for easy network-based control and configuration.
This project provides a responsive web interface for manual control and configuration, along with HTTP endpoints for integration with home automation systems like Home Assistant.
- Web-Based Control: Turn the relay ON or OFF via a web page.
- Toggle Function: Momentarily change the relay state and then revert, with a configurable pause duration.
- WiFi Configuration: Configure WiFi credentials (SSID and Password) to connect to your local network (STA mode).
- Access Point (AP) Mode: For initial configuration if STA credentials are not set or connection fails. The default AP SSID is
ESP32-Relay-Config
. - Configurable Relay Pin: Set the GPIO pin connected to the relay.
- Configurable Toggle Pause: Define the pause duration (in milliseconds) for the toggle function.
- Persistent Settings: WiFi and relay configurations are saved to Non-Volatile Storage (NVS) on the ESP32.
- Responsive Web Interface: Suitable for desktop and mobile browsers.
- HTTP Endpoints: For programmatic control and status checks.
- OTA Updates: (If
ota.cpp
and related logic from a more complete template are included - currently not detailed in this project's scope but common for ESP32 projects).
This project is designed to be built using PlatformIO.
- PlatformIO Core or PlatformIO IDE for VSCode.
- An ESP32 development board.
- A relay module compatible with ESP32 GPIO levels.
- Connect the relay module's control pin to the GPIO pin defined in
src/config.cpp
(default is23
, but configurable via the web UI). - Connect power (3.3V or 5V, depending on your ESP32 board and relay module) and GND.
- Connect the load you want to control to the relay's output terminals.
-
Clone the Repository:
git clone <repository-url> cd esp32-web-relay
-
PlatformIO Configuration:
- The
platformio.ini
file is pre-configured for a generic ESP32 dev board. - Modify
upload_port
inplatformio.ini
if your ESP32 is on a different serial port (e.g.,/dev/ttyUSB0
on Linux,COM3
on Windows). - Default relay pin is set in
src/config.cpp
(DEFAULT_RELAY_PIN
). This can be changed in the web UI after initial flashing.
- The
-
Build Firmware:
pio run
-
Build and Upload Filesystem (LittleFS): The web interface files (HTML, CSS, JS) are stored in the
data
directory and need to be uploaded to the ESP32's LittleFS filesystem.pio run -t uploadfs
-
Upload Firmware:
pio run -t upload
-
AP Mode (Initial Setup):
- If no WiFi credentials are stored, or if the ESP32 fails to connect to the configured WiFi, it will start in Access Point (AP) mode.
- The default AP SSID is
ESP32-Relay-Config
(this is defined insrc/config.cpp
asAP_SSID
). There is no password by default. - Connect your computer or smartphone to this WiFi network.
- Open a web browser and navigate to
http://192.168.4.1
(this is the default AP IP, defined asAP_LOCAL_IP_STR
insrc/config.cpp
). - You should be redirected to the configuration page (
/config.html
) to set up your WiFi network (STA mode) and relay settings.
-
STA Mode (Connected to your WiFi):
- Once configured and connected to your WiFi network, the ESP32 will get an IP address from your router.
- You can usually find this IP address in your router's DHCP client list or via the ESP32's serial monitor output during startup.
- Access the web interface by navigating to
http://<ESP32_IP_ADDRESS>
in your browser.
Method | Endpoint | Description | Response Body (Example) / Redirect |
---|---|---|---|
GET | / or /index.html |
Main control page. Redirects to /config.html if in AP mode. |
HTML page |
GET | /config.html |
WiFi and relay configuration page. | HTML page |
GET | /readme.html |
This README information page. | HTML page |
GET | /success.html |
Message display page after actions like saving config. | HTML page |
GET | /style.css |
Serves the CSS stylesheet. | CSS content |
GET | /manifest.json |
Web application manifest. | JSON content |
POST | /relay/on |
Turns the relay ON. | Redirects to / |
POST | /relay/off |
Turns the relay OFF. | Redirects to / |
POST | /relay/toggle |
Toggles the relay state (e.g., ON -> pause -> OFF -> original state). | JSON: {"state": true/false, "message": "Relay toggled..."} |
GET | /relay/state |
Gets the current relay state. | JSON: {"state": true/false} |
GET | /api/relay_config |
Gets current and default relay settings. | JSON: {"relay_pin": 23, "relay_toggle_delay_ms": 500, "default_relay_pin": 23, "default_relay_toggle_delay_ms": 500} |
GET | /wifi/status |
Gets current WiFi mode, SSID, and IP. | JSON: {"mode": "STA"/"AP", "ssid": "YourSSID", "ip": "192.168.1.123"} |
POST | /save_config |
Saves WiFi and relay configuration. Accepts form data: ssid , password , relay_pin , relay_delay . |
Redirects to /success.html or /config.html with messages. |
POST | /clear_config |
Clears saved WiFi credentials and restarts in AP mode. | Redirects to /success.html . |
GET | /api/discovered_networks |
Scans for and returns available WiFi networks. | JSON array: ["SSID1", "SSID2"] |
POST | /api/reboot |
Reboots the device. | Plain text: Rebooting... |
You can integrate this ESP32 Web Relay with Home Assistant using the RESTful integration. Replace <ESP32_IP_ADDRESS>
with the actual IP address of your ESP32 device on your network.
# Example Home Assistant configuration (configuration.yaml)
rest_command:
esp32_relay_on:
url: "http://<ESP32_IP_ADDRESS>/relay/on"
method: POST
esp32_relay_off:
url: "http://<ESP32_IP_ADDRESS>/relay/off"
method: POST
esp32_relay_toggle:
url: "http://<ESP32_IP_ADDRESS>/relay/toggle"
method: POST
sensor:
- platform: rest
name: "ESP32 Relay Raw Status"
resource: http://<ESP32_IP_ADDRESS>/relay/state
method: GET
value_template: "{{ value_json.state }}" # This will be true or false
scan_interval: 10 # Adjust as needed
force_update: true # Ensures the sensor updates even if the string value ('true'/'false') hasn't changed
switch:
- platform: template
switches:
esp32_web_relay:
friendly_name: "ESP32 Controlled Relay"
value_template: "{{ states('sensor.esp32_relay_raw_status') | lower == 'true' }}"
turn_on:
service: rest_command.esp32_relay_on
turn_off:
service: rest_command.esp32_relay_off
# To use the toggle command for the switch entity directly:
# (Be mindful of HA expecting distinct on/off if state is not immediately polled)
# turn_on:
# service: rest_command.esp32_relay_toggle
# turn_off:
# service: rest_command.esp32_relay_toggle
icon_template: >
{% if states('sensor.esp32_relay_raw_status') | lower == 'true' %}
mdi:toggle-switch-variant
{% else %}
mdi:toggle-switch-variant-off
{% endif %}
Notes for Home Assistant:
- The
scan_interval
for the REST sensor determines how frequently Home Assistant polls the ESP32 for its state. - The
rest_command
entities allow you to create buttons or call services in automations to control the relay. - The template switch uses the state from the
esp32_relay_raw_status
sensor to reflect the relay's state and to call the appropriaterest_command
. - If you use the
esp32_relay_toggle
command from Home Assistant, the state update might rely on the next poll of the/relay/state
endpoint. The toggle endpoint itself does return the final state after the toggle action, but HA's REST sensor polls independently.
- No Serial Output: Check your USB cable, drivers, and ensure the correct serial port is selected in PlatformIO.
- LittleFS Upload Fails: Ensure the ESP32 is properly connected and not in a hung state. Try holding the BOOT button while plugging it in, then release, and try uploading again.
- Cannot Connect to AP: Double-check the AP SSID (
ESP32-Relay-Config
) and ensure no password is required. Try from a different device. - Cannot Connect in STA Mode: Verify SSID and password are correct. Check router logs. Ensure the ESP32 is within WiFi range.
- Webpage Not Loading: Check IP address. Ensure the ESP32 and your client device are on the same network (in STA mode). Check serial monitor for errors.
ESP32 Web Relay Project - Enjoy!