Smart homeESPHome

Control a relay over WiFi with ESPHome

Difficulty: easy · Time: ~45 minutes

ESPHome turns an ESP32 into a smart-home device using just a YAML file. It integrates directly with Home Assistant and supports over-the-air (OTA) firmware updates.

Safety: test with a low-voltage load first (12V LED strip, 5V fan). If you switch 220V, use an opto-isolated relay module, an enclosure, wire with power disconnected, or hire an electrician.

Parts

Wiring

DeviceESP32
Relay INGPIO26
Relay VCC / GND5V (VIN) / GND
Push button (one leg)GPIO27, the other leg to GND

ESPHome configuration

esphome:
  name: living-room-light

esp32:
  board: esp32dev
  framework:
    type: esp-idf

logger:

api:
  encryption:
    key: !secret api_key

ota:
  - platform: esphome
    password: !secret ota_password

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  ap:                       # fallback hotspot if WiFi is lost
    ssid: "Living-Room-Light"
    password: !secret ap_password

captive_portal:

switch:
  - platform: gpio
    id: relay1
    name: "Living room light"
    pin: GPIO26
    restore_mode: RESTORE_DEFAULT_OFF

binary_sensor:
  - platform: gpio
    pin:
      number: GPIO27
      mode: INPUT_PULLUP
      inverted: true
    name: "Light button"
    filters:
      - delayed_on: 50ms     # debounce
    on_press:
      - switch.toggle: relay1

Steps

  1. Install ESPHome (the Home Assistant add-on, or pip install esphome).
  2. Create a secrets.yaml with wifi_ssid, wifi_password, api_key, ota_password and ap_password. The api_key is a random 32-byte base64 string; the ESPHome dashboard can generate one for you.
  3. Flash the first time over USB: esphome run living-room-light.yaml.
  4. Later updates go over WiFi (OTA). Home Assistant will discover the device automatically.

Notes