Smart home

Door/window sensor ESP32 ESPHome

Monitor a door or window: reed switch, ESP32-C6, ESPHome, wiring, YAML and Home Assistant alerts. Parts list, GPIO wiring, ESPHome YAML and Home Assistant.

Updated · Emmanuel SAUVAGE

  • LevelBeginner
  • Time1–2 h
  • Budgetabout $15–35 depending on the seller

Rough estimate, check with your seller: prices vary by shop and period.

Project goal

You will connect up to three magnetic contacts, one for a door and two for windows, to a single ESP32, a small electronic board with Wi-Fi, and see their open or closed state in Home Assistant, the software that gathers your connected devices. A magnetic contact is a small switch that closes when a magnet comes near. The build is powered over USB: it suits a room where you can run a cable from the board to the doors and windows.

Why build it

You know whether a window was left open while the heating is on, you are alerted when a door opens and you can even trigger a light. The magnetic contact is the simplest and most reliable source of information for this: it depends neither on light nor on noise, only on the real position of the door or window.

Useful terms for this project: ESP32 (small Wi-Fi board) · ESPHome (prepares the board’s program) · GPIO (the board’s pins) · OTA (update without a USB cable)

Prerequisites

  • Home Assistant with ESPHome, and a USB outlet near the board.
  • Wired alarm-type magnetic contacts with a normally open contact (closed when the magnet is in front), with their datasheet for the maximum gap.
  • Two-conductor signal cable to each opening (a few metres).

Diagrams

Wiring diagram : Door and window opening sensor
Wiring diagram : Door and window opening sensorGPIO10 → Door contact Contact A; GND → Door contact Contact B; GPIO11 → Window contact 1 Contact A; GND → Window contact 1 Contact B; GPIO18 → Window contact 2 Contact A; GND → Window contact 2 Contact BESP32-C6 DevKitC-1Door contactGPIO10Contact AGNDContact BWindow contact 1GPIO11Contact AGNDContact BWindow contact 2GPIO18Contact AGNDContact BData or signalGround (GND)
Principle diagram : Door and window opening sensor
Principle diagram : Door and window opening sensorMagnetic contacts → ESP32-C6 + ESPHome → Home AssistantMagnetic contactsOne dry contact per openingClosed near the magnet, open otherwiseGPIO10, GPIO11 and GPIO18 to GNDESP32-C6 + ESPHomeInputs with internal pull-up100 ms debounce2.4 GHz Wi-Fi + encrypted APIHome AssistantDoor and window entities (open or closed)Alert and heating cut-off

Parts list

This ESP32 board is the base for every project in the series. ESPHome also works with other ESP32 boards: the board-choice guide helps you compare them. Which ESP32 board to choose?

ESP32-C6-DevKitC-1

Suggested board

ESP32-C6-DevKitC-1

check with the seller
  • Wi-Fi 6, Bluetooth 5, Zigbee and Thread (at hardware level)
  • Supported by ESPHome (ESP-IDF framework)
  • USB-C for flashing and power

Watch-outs

  • 2.4 GHz Wi-Fi only
  • Use a USB cable that carries data

Main components

ItemQuantityRole and precautions
ESP32-C6-DevKitC-11Control board (see the box above).
Wired magnetic contact (reed) with normally open contact1 to 3One per door or window. Check the maximum magnet-to-contact gap in the datasheet. Main component: search for « wired magnetic door window contact reed switch normally open » at your seller (affiliate link, check price and availability).
2-conductor signal cable2 to 10 m per contactLow voltage only; avoid running it alongside mains cables. Main component: search for « wired magnetic door window contact reed switch normally open » at your seller (affiliate link, check price and availability).

Small parts

ItemQuantityRole and precautions
USB-C data cable1For flashing and power. Charge-only cables do not carry data.
USB 5 V power supply (CE/UKCA-marked charger)1At least 1 A for the board alone; more if peripherals draw power from it.
Dupont jumper wires (male-female and female-female)1One mixed pack covers every prototype.
Low-voltage screw terminals or lever connectors1To connect sensor or dry-contact wires cleanly.
Assorted 1/4 W resistors1Handy for pull-ups (4.7 kΩ to 10 kΩ) and protection (330 Ω).
Vented plastic or 3D-printed enclosure1Protects the board; leave a cable gland and vents if the sensor measures air.

Amazon links are affiliate links: the site may earn a commission at no extra cost to you.

Step-by-step build

Step 1. Prepare ESPHome and create the device

  1. In Home Assistant, open the ESPHome Device Builder add-on (see the tutorial “Install ESPHome in Home Assistant (Device Builder)”). ESPHome is the software that turns a simple settings file into the program for your ESP32 board, without you having to write any code.
  2. Open “Secrets” (top right): this file keeps your passwords apart, so you can share your configurations without revealing them. Check that wifi_ssid (the name of your Wi-Fi network), wifi_password, api_encryption_key (the key that encrypts the link with Home Assistant), ota_password (for updates without a cable) and ap_password (for the board’s fallback Wi-Fi network) exist, and add any missing line. A valid API key is a long 32-byte string encoded in base64, which you can generate with “openssl rand -base64 32”.
  3. Click “New device”, name it “capteur-ouvertures”, pick ESP32-C6, skip the flash for now, then replace the file content with the YAML from this page (“Edit”). YAML is a configuration file written in plain text: it describes, line by line, what the board must do.

What you should see: The file opens in the editor with syntax highlighting and no red underline.

Check: The “Validate” action (⋮ menu) answers “Configuration is valid”.

Step 2. Wire the contacts

  1. With the USB power unplugged, connect one of each contact’s two wires to GND, the ground, or to a common wire that joins GND, which saves cable.
  2. Connect the other wire of the door contact to GPIO10, window 1’s to GPIO11 and window 2’s to GPIO18: these are GPIOs, the metal pins lined up along the edge of the board, and each contact uses one.
  3. For the test, place each contact on the desk with its magnet.

What you should see: Each contact is a plain dry switch, with no voltage of its own.

Check: Each contact is wired between a GPIO pin and GND, never on 3V3 or 5V.

Step 3. Flash the board and add it to Home Assistant

  1. Connect the board to your computer with the USB-C data cable: “flashing” means writing the program into the board’s memory, and this first write must be done over a cable. The board can already be wired or sitting on the breadboard, but any external peripheral with its own power supply must stay switched off.
  2. In ESPHome click “Install”, then “Plug into this computer” (Chrome or Edge over HTTPS) or “Manual download” and upload the file with ESPHome Web (web.esphome.io). If the port is missing, follow the flashing tutorial.
  3. After the reboot open Settings → Devices & services: the ESPHome device is discovered; click “Configure” and paste the API encryption key.

What you should see: The “Logs” show the Wi-Fi connection and then “Successfully connected to Home Assistant”.

Check: The device appears under Devices & services → ESPHome with its entities; later updates need no cable and go over Wi-Fi (this is OTA, “Over The Air”).

Step 4. Test every contact’s state

  1. In Home Assistant, open the ESPHome device: “Front door”, “Window 1” and “Window 2” appear, one per contact.
  2. Bring the magnet near a contact: the state goes “Closed”; move it away: “Open”.
  3. Repeat for each of the three contacts.

What you should see: The state changes instantly, with no visible bounce.

Check: If the state is inverted (normally closed contact), add “inverted: true” to that pin.

Step 5. Fix the contacts on the openings

  1. Fix the contact on the fixed frame and the magnet on the moving part, face to face with a gap of a few millimetres when the door or window is closed: beyond the distance given in the instructions, the contact would no longer sense the magnet.
  2. Close the opening and check the entity goes “Closed”; open it a few centimetres: “Open”.
  3. Fix and protect the cable, then connect it to the board with a terminal block.

What you should see: The entity changes state as soon as the opening moves a few centimetres.

Check: If detection is erratic, bring the magnet closer or check alignment: the maximum gap depends on the model.

Step 6. Create the “forgotten window” alert

  1. An automation is an “if… then…” rule that Home Assistant applies by itself. Open Settings → Automations & scenes → Create automation.
  2. Trigger: “Window 1” stays “on” for 10 minutes. Condition (optional): outdoor temperature below 10 °C. Action: phone notification.
  3. Test by leaving the window open for more than 10 minutes.

What you should see: The notification arrives only after 10 minutes open.

Check: Close the window: no notification must follow.

ESPHome code (YAML)

YAML is a configuration file written in plain text: it tells ESPHome what the board must do. Paste this one into ESPHome after creating the device. It targets an ESP32-C6 board; values to personalise are marked with “CHANGE” comments.

esphome:
  name: capteur-ouvertures
  friendly_name: Door and window sensor

esp32:
  board: esp32-c6-devkitc-1   # XIAO ESP32C6: use board: seeed_xiao_esp32c6
  framework:
    type: esp-idf             # required for ESP32-C6

logger:                       # serial logs, also visible over Wi-Fi

api:
  encryption:
    key: !secret api_encryption_key

ota:
  - platform: esphome
    password: !secret ota_password

wifi:
  ssid: !secret wifi_ssid       # 2.4 GHz network only
  password: !secret wifi_password
  ap:                           # fallback hotspot if the Wi-Fi is unreachable
    ssid: "capteur-ouvertures fallback"
    password: !secret ap_password

captive_portal:

binary_sensor:
  - platform: gpio
    name: "Front door"
    pin:
      number: GPIO10
      mode: INPUT_PULLUP         # contact between GPIO10 and GND
    device_class: door           # ON = open, OFF = closed
    filters:
      - delayed_on: 100ms        # ignores contact bounce
      - delayed_off: 100ms

  - platform: gpio
    name: "Window 1"
    pin:
      number: GPIO11
      mode: INPUT_PULLUP
    device_class: window
    filters:
      - delayed_on: 100ms
      - delayed_off: 100ms

  - platform: gpio
    name: "Window 2"
    pin:
      number: GPIO18
      mode: INPUT_PULLUP
    device_class: window
    filters:
      - delayed_on: 100ms
      - delayed_off: 100ms

  - platform: status
    name: "Openings sensor status"

sensor:
  - platform: wifi_signal
    name: "WiFi signal"
    update_interval: 120s
    entity_category: diagnostic

YAML comments are in English, as in the ESPHome documentation. This code has not been run on your hardware: use “Validate” before flashing and adjust pins and names.

Home Assistant integration

  • With the “door” or “window” class, Home Assistant shows “Open” or “Closed” and the right icon with no extra setup.
  • Use these entities as conditions: for example, do not turn on a room’s heating while its window is open.
  • A dashboard card “Openings” can group the three entities to see the state of the house at a glance.

Common problems and troubleshooting

SymptomFix
The state is invertedYour contact is normally closed: add “inverted: true” to the pin or change the contact.
Spurious state changesThe cable picks up noise. Move the board closer, keep the cable away from mains lines, add a 10 kΩ external pull-up to 3V3 and raise delayed_on.
The contact does not detect the magnetThe gap is too large or the magnet is badly oriented. Check the contact datasheet and bring both parts closer.
No entity in Home AssistantCheck the board’s Wi-Fi connection and the ESPHome log for configuration errors.

FAQ

Can I power it with a battery?

Not with this build: Wi-Fi uses a lot of power. For a wireless battery-powered opening sensor a commercial Zigbee sensor is a better fit.

How many contacts can I connect?

As many as there are free input pins on the board; three are shown here, but the ESP32-C6 has more, apart from boot-reserved pins.

Does it work as an alarm?

It informs but does not replace a certified alarm: it depends on Wi-Fi, the server and power.

Related tutorials

These step-by-step guides explain the gestures common to every project in the series.

Other ESP32 projects

Sources and documentation

Cette page vous a-t-elle été utile ?

Have a question about this guide or need advice? Ask us here

Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.