In this tutorial, you’ll learn how to make a battery-powered Zigbee door sensor with an ESP32-H2 board. It tells Home Assistant when a door opens or closes. You program it with the Arduino IDE, just like an Arduino board.
The same setup works for anything with a switch that opens and closes: a window, a mailbox lid, a cabinet, or a switch that detects if a door is locked.
The whole program does just three things:
- Wake up and read the switch.
- Send “open” or “closed” to Home Assistant over Zigbee.
- Go into deep sleep until the switch changes.
Because it sleeps almost all the time, it can run on a battery for a long time.
Why the ESP32-H2? Unlike most ESP32 boards, the H2 has no Wi-Fi. Instead, it has a Zigbee radio. Zigbee uses much less power than Wi-Fi, and it connects directly to the Zigbee network you probably already have for your smart home devices.
Table of Contents:
- What You Need
- Step 1: Add ESP32 Support to the Arduino IDE
- Step 2: Connect the Board and Choose the Settings
- Step 3: Test It on USB and Connect It to Home Assistant
- Step 4: Set It Up in Home Assistant
- Step 5: Make It Run on a Battery
- Troubleshooting
What You Need
| Part | Notes |
|---|---|
| ESP32-H2 board | I used the ESP32-H2-DevKitM-1, Espressif’s own development board. Get it from DigiKey |
| Reed switch + magnet | The magnet sits on the door, the reed switch on the frame. A microswitch also works |
| LiFePO4 battery (14500, AA size) | 3.2 V, can connect straight to the 3.3 V pin. Only needed for the battery version |
| USB cable | For programming and testing |
You don’t need a pull-up resistor. We’ll use the one built into the ESP32-H2.
On the software side, you need:
Basic Electronics for Arduino Makers
Learn the basics that every Arduino maker should know, and it'll open you up to a world of possibilities! Sign up for my circuit tips by email and I'll send you the eBook:
- Arduino IDE 2
- Home Assistant with a Zigbee coordinator (a USB Zigbee dongle)
- A Zigbee integration in Home Assistant: either ZHA (built in) or Zigbee2MQTT
Why not two AA batteries? The ESP32-H2 needs at least 3.0 V. Two fresh AA batteries give about 3.0–3.2 V, so the voltage drops too low long before the batteries are empty.
Step 1: Add ESP32 Support to the Arduino IDE
The Arduino IDE doesn’t know about ESP32 boards out of the box, so you need to install the ESP32 board package. It includes the Zigbee library we’ll use.
- Open the Arduino IDE.
- Go to Tools → Board → Boards Manager.
- Search for esp32 and install esp32 by Espressif Systems. Make sure it’s version 3.x or newer, since older versions don’t have the Zigbee library.
- If it doesn’t show up in the search, go to File → Preferences and add this to Additional boards manager URLs:
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonThen try the search again.


The package is large, since it includes compilers and libraries for all the ESP32 chips. Depending on your internet speed, the install can take a while. For me, it took 20–30 minutes. This tutorial was tested with version 3.3.12.
Step 2: Connect the Board and Choose the Settings
Connect the board to your computer with a USB cable. The ESP32-H2-DevKitM-1 has two USB ports, marked UART and USB. Use the UART port.

The UART port goes through a USB-to-serial chip on the board. That chip stays on while the ESP32-H2 sleeps, so the Serial Monitor keeps working when we add deep sleep later. The USB port shuts off when the chip sleeps.
On Windows, the driver for the USB-to-serial chip should install automatically when you plug in the board.
Then set up the Tools menu. Zigbee needs a few special settings. If you skip these, the code won’t compile, or the board won’t join the network.
| Setting (Tools menu) | Choose |
|---|---|
| Board | ESP32H2 Dev Module |
| Port | The COM port that appeared when you plugged in the board |
| Zigbee mode | Zigbee ED (end device) |
| Partition Scheme | Zigbee 4MB with spiffs (not “Default 4MB with spiffs”) |
| Erase All Flash Before Sketch Upload | Disabled (see below if the board won’t join) |
“End device” means the board is a simple sensor that talks to the network, but doesn’t pass messages on for other devices. That’s what you want for a battery-powered sensor.
A new board doesn’t need its flash erased. But if the board has been used for Zigbee before, or it won’t join your network in Step 3, set Erase All Flash Before Sketch Upload to Enabled for one upload. That wipes any old Zigbee network data. Then set it back to Disabled, or the board will forget the network every time you upload new code.
Step 3: Test It on USB and Connect It to Home Assistant
Before adding batteries and sleep, test that the board can join your Zigbee network. The ESP32 package comes with a contact sensor example that does almost exactly what we need.
Upload the Example
- Go to File → Examples → Zigbee → Zigbee_Contact_Switch. Open it from this menu, not from GitHub. The GitHub version can be newer than the library you have installed, and then it won’t compile.
- Change
sensor_pinfrom4to10. We’ll need pin 10 later for deep sleep. - Change the name line to:
zbContactSwitch.setManufacturerAndModel("DIY", "ESP32H2_Door_Sensor"); - Connect the reed switch between pin 10 and GND.
Move parts around or plan your own build. Free in your browser, no signup needed.
- Upload the code and open the Serial Monitor at 115200 baud. The first compile can take a couple of minutes, since the Zigbee library is big.
Pair It With Home Assistant
Home Assistant has two common ways to connect Zigbee devices:
- ZHA (Zigbee Home Automation) is built into Home Assistant. It’s the simplest to set up.
- Zigbee2MQTT is a separate app that runs next to Home Assistant. It also needs an MQTT broker, usually Mosquitto.
Both work with this sensor, so use the one you already have. To pair the sensor:
- Put your Zigbee network in pairing mode:
- ZHA: Go to Settings → Devices & services → Zigbee Home Automation and click Add device.
- Zigbee2MQTT: In the Zigbee2MQTT web page, click Permit join (All).
- Press the reset button on the ESP32-H2. The Serial Monitor should print dots while it connects, then stop when it has joined.
- The sensor shows up as a new device. Move the magnet to and from the reed switch and check that the state changes.

When pairing works, the Serial Monitor ends like this:

In Zigbee2MQTT, the sensor shows up with two values called alarm_1 and alarm_2. That’s how Zigbee2MQTT shows sensors it doesn’t have a specific profile for. The two always have the same value, so you only need one. We’ll use alarm_1: it’s true when the switch is open and false when it’s closed. You can disable the alarm_2 entity in Home Assistant to keep things tidy.
If pairing fails with “Interview failed,” remove the device and try again. It can take a couple of tries.
Step 4: Set It Up in Home Assistant
Once paired, the sensor is added to Home Assistant automatically. It shows up as a binary sensor that is either open or closed.
To make it look right on your dashboard:
- In Home Assistant, go to Settings → Devices & services → Entities and find the sensor’s entity. With ZHA, there’s just one. With Zigbee2MQTT, pick the one ending in alarm_1.
- Click it, then click the gear icon.
- Give it a name, like “Front door.”
- Set Show as to what it’s used for, like Door, Window, or Garage door. You get the matching icon and state names.
If you use the switch to detect a lock, choose Lock. Then “closed” shows as “Locked” and “open” as “Unlocked.”

Before you upload any new code: check that Erase All Flash Before Sketch Upload is set to Disabled. Otherwise, the board forgets the pairing, and you have to pair it again.
Step 5: Make It Run on a Battery
The example code stays awake all the time and checks the switch over and over. That drains a battery in days. To make it last, the board must sleep and only wake up when the switch changes.
The Circuit
The wiring stays the same: the reed switch between pin 10 and GND. The ESP32-H2’s built-in pull-up resistor keeps the pin HIGH when the switch is open.
Change values or swap parts. Free in your browser, no signup needed.
Why pin 10? Only GPIO 7 to 14 can wake the ESP32-H2 from deep sleep. Avoid 8 and 9, since they’re used when the chip boots.
How the Code Works
The whole program runs in setup(). It reads the switch, joins the network, sends the state, and goes to sleep. loop() is never reached.
The interesting part is how it wakes up both when the door opens and when it closes. Right before sleeping, it reads the pin. If the pin is HIGH, it tells the chip to wake up when the pin goes LOW. If it’s LOW, it wakes up when it goes HIGH. So any change wakes it up.
It also wakes up every 6 hours and sends the state again, so Home Assistant knows it’s still alive.
The pull-up keeps working while the chip sleeps, because the ESP32-H2 holds the state of the wake-up pin during deep sleep.
After joining, the sensor must also be “enrolled.” That’s how a Zigbee security sensor registers with the system that listens for its alarms. The first time, the board asks for a new enrollment. It then saves an “enrolled” flag in flash and restores the enrollment on every wake-up, which is much faster. The code uses the same flag as the example from Step 3, so a board paired with the example keeps working.
The example’s “hold BOOT for 3 seconds” reset doesn’t work here, since the board is asleep most of the time. To reset the pairing, upload the code once with Erase All Flash Before Sketch Upload set to Enabled. That clears both the Zigbee network data and the enrolled flag. Then set it back to Disabled.
The Code
#ifndef ZIGBEE_MODE_ED
#error "Select Tools -> Zigbee mode: Zigbee ED (end device)"
#endif
#include "Zigbee.h"
#include <Preferences.h>
#define SENSOR_PIN 10 // Must be GPIO 7-14 to wake the ESP32-H2 from deep sleep
#define ENDPOINT 1 // Same endpoint as the example you paired with
#define CHECKIN_HOURS 6 // Wake up anyway every few hours so Home Assistant knows we're alive
ZigbeeContactSwitch zbContact = ZigbeeContactSwitch(ENDPOINT);
Preferences preferences; // Stores the "enrolled" flag in flash
bool readIsOpen() {
return digitalRead(SENSOR_PIN) == HIGH;
}
void sendState(bool isOpen) {
if (isOpen) {
zbContact.setOpen();
Serial.println("Sent: OPEN");
} else {
zbContact.setClosed();
Serial.println("Sent: CLOSED");
}
}
void goToSleep() {
// Wake up when the pin changes: if it's HIGH now, wake on LOW, and the other way around
bool isOpen = readIsOpen();
esp_sleep_enable_ext1_wakeup(1ULL << SENSOR_PIN,
isOpen ? ESP_EXT1_WAKEUP_ANY_LOW : ESP_EXT1_WAKEUP_ANY_HIGH);
// Also wake up on a timer, as a "still alive" check-in
esp_sleep_enable_timer_wakeup((uint64_t)CHECKIN_HOURS * 3600ULL * 1000000ULL);
Serial.println("Going to sleep");
Serial.flush();
esp_deep_sleep_start();
}
void setup() {
Serial.begin(115200);
pinMode(SENSOR_PIN, INPUT_PULLUP); // Built-in pull-up resistor
// Has this board been enrolled before? (Same flag as the example uses)
preferences.begin("Zigbee", false);
bool enrolled = preferences.getBool("ENROLLED");
preferences.end();
// Set up the Zigbee device
zbContact.setManufacturerAndModel("DIY", "ESP32H2_Door_Sensor");
zbContact.setPowerSource(ZB_POWER_SOURCE_BATTERY);
Zigbee.addEndpoint(&zbContact);
// Settings for a sleepy end device (from Espressif's sleepy sensor example)
esp_zb_cfg_t zigbeeConfig = ZIGBEE_DEFAULT_ED_CONFIG();
zigbeeConfig.nwk_cfg.zed_cfg.keep_alive = 10000;
Zigbee.setTimeout(10000);
if (!Zigbee.begin(&zigbeeConfig, false)) {
Serial.println("Zigbee failed to start");
goToSleep();
}
// Wait for the network, but give up after 10 seconds to save the battery
unsigned long start = millis();
while (!Zigbee.connected()) {
if (millis() - start > 10000) {
Serial.println("No network, sleeping");
goToSleep();
}
delay(100);
}
// Restore the enrollment from flash, or ask for a new one the first time
if (enrolled) {
zbContact.restoreIASZoneEnroll();
} else {
zbContact.requestIASZoneEnroll();
}
start = millis();
while (!zbContact.enrolled()) {
if (millis() - start > 10000) {
Serial.println("Not enrolled, sleeping");
goToSleep();
}
delay(100);
}
// Save the flag the first time, so we can restore it after every wake-up
if (!enrolled) {
preferences.begin("Zigbee", false);
preferences.putBool("ENROLLED", true);
preferences.end();
}
// Send the state, then send again if it changed while we were busy
bool sentState = readIsOpen();
sendState(sentState);
delay(1000); // Give the radio time to deliver the message
if (readIsOpen() != sentState) {
sendState(readIsOpen());
delay(1000);
}
goToSleep();
}
void loop() {
// Never reached - the board sleeps at the end of setup()
}
Upload it with the same Tools settings as before. Since the board already joined the network in Step 3, keep Erase All Flash Before Sketch Upload set to Disabled so it keeps the pairing. If you erase it, just pair it again.
Test It
Open the Serial Monitor and open and close the door. Each time, you should see the board wake up, send the new state, and go back to sleep. Check that Home Assistant updates within a few seconds.
Here’s what the Serial Monitor shows when the door opens and then closes:
ESP-ROM:esp32h2-eco5-20240613
Build:Jun 13 2024
rst:0x5 (SLEEP_WAKEUP),boot:0xc (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x408460f0,len:0x1214
load:0x4083c2d0,len:0xd6c
load:0x4083efd0,len:0x2f7c
entry 0x4083c2d0
Sent: OPEN
Going to sleep
ESP-ROM:esp32h2-eco5-20240613
Build:Jun 13 2024
rst:0x5 (SLEEP_WAKEUP),boot:0xc (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x408460f0,len:0x1214
load:0x4083c2d0,len:0xd6c
load:0x4083efd0,len:0x2f7c
entry 0x4083c2d0
Sent: CLOSED
Going to sleep
The lines at the top of each block are the chip starting up. rst:0x5 (SLEEP_WAKEUP) tells you it woke up from deep sleep. After that, you should see one “Sent” line and “Going to sleep.”
In my test, Home Assistant updated about one second after the switch changed.
Power It From the Battery
Connect the LiFePO4 battery’s + to the 3.3 V pin and – to GND. Don’t connect USB at the same time.
Optional: Make the Battery Last Longer
The built-in pull-up is around 45 kΩ. That’s the typical value Espressif lists for its ESP32 chips, and the exact value varies a bit from chip to chip. While the switch is closed, it draws about 3.3 V / 45 kΩ ≈ 70 µA. A door is usually closed, so this current flows most of the time. On a 14500 LiFePO4 battery, that alone uses up the battery in roughly 8 to 12 months.
If you want it to last longer, use a 1 MΩ resistor between pin 10 and 3.3 V instead, and change INPUT_PULLUP to INPUT in the code. Now the switch only draws 3.3 V / 1 MΩ = 3.3 µA.
Troubleshooting
| Problem | Try this |
|---|---|
| Code won’t compile: “Zigbee end device mode is not selected” | Set Tools → Zigbee mode to Zigbee ED (end device) |
| Code won’t compile: missing functions | Open the example from File → Examples, not GitHub, and check you have ESP32 package 3.x |
| Board crashes and restarts: “Failed to find zb_storage partition” | The wrong partition scheme is selected. Set Tools → Partition Scheme to Zigbee 4MB with spiffs and upload again |
| Board never joins the network | Set Erase All Flash Before Sketch Upload to Enabled, upload again, and turn on pairing mode before resetting the board |
| “Interview failed” in Zigbee2MQTT | Remove the device in Zigbee2MQTT. The board rejoins by itself while Permit join is on. It can take a couple of tries, and it helps to have the board close to the Zigbee dongle |
| Joins once, but not after sleep or power off | Make sure Erase All Flash is Disabled when uploading the battery version. If it still fails, remove the device from ZHA or Zigbee2MQTT and pair it again |
| Nothing in the Serial Monitor | Check the baud rate (115200) and that the cable is in the UART port. On the USB port, you need to set Tools → USB CDC On Boot to Enabled |
| Serial Monitor disconnects all the time | Use the UART port, since the USB port shuts off when the chip sleeps. You can also comment out goToSleep() at the end of setup() while you debug |
| Home Assistant shows the opposite state | Use a normally open reed switch, so it’s closed when the magnet is close (door closed) |
A failed interview shows up in Zigbee2MQTT as a device with a warning icon:

More Arduino Tutorials
Basic Electronics for Arduino Makers
Learn the basics that every Arduino maker should know, and it'll open you up to a world of possibilities! Sign up for my circuit tips by email and I'll send you the eBook: