ESP32 Smart Curtain Opener with Stepper, LDR, OLED & Web Control

Connection diagram of the ESP32 smart curtain opener with 28BYJ-48 stepper on a ULN2003 driver, limit switch, push button, LDR sensor and SSD1306 OLED

Build an ESP32 smart curtain opener that pulls the curtain cord with a 28BYJ-48 stepper, opens with daylight or at a set time, and is controlled from a phone web page, a push button and an OLED status screen.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUESP32 DevKit V1
  • Parts9 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Opening the curtains every morning and closing them every evening is a small job that is easy to forget. This ESP32 smart curtain opener does it for you. A 28BYJ-48 stepper motor pulls the curtain cord loop, a limit switch tells the ESP32 where “fully closed” is, and an LDR watches the daylight. You can open or close the curtain from a phone web page, set it to any position with a slider, give it daily open and close times, or let it follow the sun. A push button on the box and a small OLED screen work even when Wi-Fi is down.

The project needs no cloud service and no app: the ESP32 hosts its own page at http://curtain.local and gets the time from an NTP server. It suits light curtains on a cord or rail loop; for heavy curtains, see the ideas section for a stronger motor.

Connection diagram of the ESP32 smart curtain opener with 28BYJ-48 stepper on a ULN2003 driver, limit switch, push button, LDR sensor and SSD1306 OLED

How It Works

  • Stepper drive: the 28BYJ-48 is a geared stepper with about 4096 half-steps per output turn, so it is slow but strong and very precise. The ESP32 drives its four coils through the ULN2003 transistor array using an 8-step half-step pattern. Stepping is non-blocking: runMotor() makes one half-step only when 1.2 ms has passed, so the web page, button and screen stay responsive while the curtain moves. The coils are switched off when the motor stops, so the motor stays cool.
  • Position and homing: position 0 is “fully closed” and TRAVEL_DEFAULT half-steps is “fully open” (20480 = 5 output turns by default). At power-up the ESP32 turns the motor toward the closed end until the limit switch is pressed, then sets the position to 0. The switch is also checked during every closing move, so the motor can never wind past the end.
  • Light mode: the LDR and 10 kΩ resistor form a voltage divider on GPIO34 (an ADC1 pin that works together with Wi-Fi). More light gives a higher reading (0–4095). When the reading stays above the “bright” level for 60 seconds the curtain opens; when it stays below the “dark” level for 60 seconds it closes. The 60-second wait stops passing clouds or car headlights from moving the curtain.
  • Daily timers: after joining Wi-Fi the ESP32 sets its clock from pool.ntp.org with the Indian time zone (IST-5:30). Once a minute it compares the time with the open and close times you saved on the web page. Settings are kept in flash with the Preferences library, so they survive a power cut.
  • Controls and display: a short press of the button opens a closed curtain, closes an open one, or stops it while it is moving. The OLED shows the state (OPENING, CLOSING, OPEN, CLOSED), the percent open with a bar, the light reading, the time and the IP address. The web page polls /data every second for a small JSON reply.

Components Required

  • ESP32 DevKit V1 (30-pin) board – 1
  • 28BYJ-48 5 V stepper motor with ULN2003 driver board – 1
  • 0.96 inch SSD1306 I2C OLED display, 128×64 – 1
  • Micro limit switch (roller lever, normally open) – 1
  • 6 mm tactile push button – 1
  • LDR (photoresistor, 5 mm) and 10 kΩ resistor – 1 each
  • 5 V 2 A DC adapter with DC jack breakout – 1
  • GT2 pulley or 3D-printed cord spool, curtain cord loop and small mounting bracket – 1 set
  • Breadboard or perfboard and jumper wires – 1 set

Wiring Table

Module pinESP32 pinNotes
ULN2003 IN1GPIO26Coil A
ULN2003 IN2GPIO25Coil B
ULN2003 IN3GPIO33Coil C
ULN2003 IN4GPIO32Coil D
ULN2003 + (5–12 V)VIN / adapter +5 VRemove the ULN2003 power jumper only if you add a separate motor switch
ULN2003 – (GND)GNDMust share ground with the ESP32
28BYJ-48 5-pin plugULN2003 motor socketThe plug is keyed; push it fully in
5 V adapter +VINPowers the ESP32 through its regulator; do not plug in USB and the adapter if your board lacks a VIN diode
5 V adapter –GNDCommon ground
OLED VCC / GND3V3 / GNDCheck the pin order printed on your module
OLED SDA / SCLGPIO21 / GPIO22Default ESP32 I2C pins, address 0x3C
LDR leg 13V3Polarity does not matter
LDR leg 2GPIO34Also connect the 10 kΩ resistor from GPIO34 to GND
Limit switch COMGPIO13Internal pull-up enabled in the code
Limit switch NOGNDMount it so the curtain (or a stop on the cord) presses it when fully closed
Push buttonGPIO27 and GNDPressed = LOW

Connection Diagram

The diagram near the top of this post shows the full layout with the power supply. The drawing below lists every ESP32 pin and what it connects to, and matches the wiring table and the code.

ESP32 Smart Curtain Opener – Pin-Accurate Wiring ESP32 DevKit V1 GPIO26 ULN2003 IN1 GPIO25 ULN2003 IN2 GPIO33 ULN2003 IN3 GPIO32 ULN2003 IN4 (motor plugs into the 5-pin socket) VIN (5 V) 5 V adapter + and ULN2003 +5V GND Adapter -, ULN2003 GND, OLED GND, switch, button, 10k 3V3 OLED VCC and one leg of the LDR GPIO21 (SDA) OLED SDA GPIO22 (SCL) OLED SCL GPIO34 (ADC) LDR other leg + 10k resistor to GND GPIO13 Limit switch COM; NO contact to GND GPIO27 Push button; other leg to GND Stepper current comes from the 5 V adapter, never from the 3V3 pin. All grounds are joined.
Pin-accurate connection diagram for the ESP32 smart curtain opener.

Mechanical Setup

  • Most window curtains on a rail have a cord loop. Fit a pulley or a printed spool with a groove on the motor shaft and wrap the cord once around it, so turning the motor one way opens the curtain and the other way closes it.
  • Fix the motor to the wall or window frame with a small bracket and pull the cord tight with a tension pulley at the bottom, so it cannot slip.
  • Mount the limit switch where the curtain edge or a bead clamped on the cord presses it at the fully closed position.
  • If the curtain moves the wrong way, swap the IN1/IN4 and IN2/IN3 wires, or simply rotate the motor mounting so the cord wraps the other way.

Code

Install the ESP32 boards package (by Espressif) in the Arduino IDE, select ESP32 Dev Module, and install Adafruit SSD1306 and Adafruit GFX from the Library Manager. WiFi, WebServer, ESPmDNS and Preferences come with the ESP32 core. Replace YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD with your own network details. The sketch was compile-checked for the ESP32 Dev Module (about 79% of the default app partition).

/*
  ESP32 Smart Curtain Opener
  28BYJ-48 stepper + ULN2003, home limit switch, LDR auto mode,
  daily open/close times (NTP), SSD1306 OLED and a Wi-Fi web page.
  Project #73 - ardiunoprojecthub.online

  Pins (ESP32 DevKit V1):
    ULN2003 IN1..IN4 -> GPIO26, GPIO25, GPIO33, GPIO32
    Limit switch (curtain fully CLOSED) -> GPIO13 to GND (INPUT_PULLUP)
    Push button (open / stop / close)   -> GPIO27 to GND (INPUT_PULLUP)
    LDR divider (LDR to 3V3, 10k to GND) -> GPIO34 (ADC1)
    OLED SDA -> GPIO21, OLED SCL -> GPIO22
*/
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Preferences.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <time.h>

// ---------- user settings ----------
const char* WIFI_SSID = "YOUR_WIFI_SSID";       // put your Wi-Fi name here
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";   // put your Wi-Fi password here
const char* TZ_INFO   = "IST-5:30";             // POSIX time zone (India)
const long  TRAVEL_DEFAULT = 20480;             // half-steps from closed to open (5 turns)
const uint16_t STEP_US = 1200;                  // time per half-step (lower = faster)

// ---------- pins ----------
const uint8_t COIL[4] = {26, 25, 33, 32};
const uint8_t PIN_LIMIT  = 13;
const uint8_t PIN_BUTTON = 27;
const uint8_t PIN_LDR    = 34;

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WebServer server(80);
Preferences prefs;

// half-step sequence for the 28BYJ-48 (IN1..IN4)
const uint8_t SEQ[8][4] = {
  {1,0,0,0},{1,1,0,0},{0,1,0,0},{0,1,1,0},
  {0,0,1,0},{0,0,1,1},{0,0,0,1},{1,0,0,1}
};

long position = 0;        // 0 = closed, travel = fully open
long target = 0;
long travel = TRAVEL_DEFAULT;
bool homed = false;
int  seqIndex = 0;
unsigned long lastStepUs = 0;
int  lastDir = 1;         // direction of the last move (for the button)

bool autoLight = false;   // LDR auto mode
int  ldrOpen = 2600;      // ADC above this = bright -> open
int  ldrClose = 900;      // ADC below this = dark -> close
int  openMin = 7 * 60;    // schedule open time (minutes after midnight), -1 = off
int  closeMin = 19 * 60;  // schedule close time, -1 = off
int  lastSchedMin = -1;
int  ldrValue = 0;
unsigned long brightSince = 0, darkSince = 0;

// ---------- motor ----------
void coilsOff() { for (int i = 0; i < 4; i++) digitalWrite(COIL[i], LOW); }

void stepOnce(int dir) {
  seqIndex = (seqIndex + dir + 8) % 8;
  for (int i = 0; i < 4; i++) digitalWrite(COIL[i], SEQ[seqIndex][i]);
  position += dir;
}

int percentOpen() { return (int)constrain(position * 100L / travel, 0L, 100L); }

void moveToPercent(int pct) {
  pct = constrain(pct, 0, 100);
  target = travel * pct / 100;
  if (target != position) lastDir = (target > position) ? 1 : -1;
}

void stopMotor() { target = position; coilsOff(); prefs.putLong("pos", position); }

// called every loop: makes at most one half-step, never blocks
void runMotor() {
  if (position == target) return;
  if (micros() - lastStepUs < STEP_US) return;
  lastStepUs = micros();
  int dir = (target > position) ? 1 : -1;
  if (dir < 0 && digitalRead(PIN_LIMIT) == LOW) {   // reached the closed end
    position = 0; target = 0; coilsOff(); prefs.putLong("pos", 0);
    return;
  }
  stepOnce(dir);
  if (position == target) { coilsOff(); prefs.putLong("pos", position); }
}

// drive toward the limit switch at boot so position 0 is exact
void homeCurtain() {
  oled.clearDisplay(); oled.setCursor(0, 0); oled.println("Homing..."); oled.display();
  long maxSteps = travel + 4096;
  while (digitalRead(PIN_LIMIT) == HIGH && maxSteps-- > 0) {
    stepOnce(-1);
    delayMicroseconds(STEP_US);
    if ((maxSteps & 255) == 0) yield();
  }
  coilsOff();
  homed = (digitalRead(PIN_LIMIT) == LOW);
  position = 0; target = 0;
  Serial.println(homed ? "Homed at limit switch" : "Limit switch not found!");
}

// ---------- button: short press = open / close / stop ----------
void checkButton() {
  static bool last = HIGH;
  static unsigned long tDown = 0;
  bool now = digitalRead(PIN_BUTTON);
  if (now != last) {
    if (now == LOW) tDown = millis();
    else if (millis() - tDown > 40) {               // released after a clean press
      if (position != target) stopMotor();          // moving -> stop
      else if (percentOpen() >= 50) moveToPercent(0);
      else moveToPercent(100);
    }
    last = now;
  }
}

// ---------- automatic modes ----------
void checkAuto() {
  static unsigned long lastRead = 0;
  if (millis() - lastRead < 1000) return;
  lastRead = millis();
  ldrValue = analogRead(PIN_LDR);

  // daily schedule from NTP time
  struct tm t;
  if (getLocalTime(&t, 10)) {
    int m = t.tm_hour * 60 + t.tm_min;
    if (m != lastSchedMin) {
      if (m == openMin)  moveToPercent(100);
      if (m == closeMin) moveToPercent(0);
      lastSchedMin = m;
    }
  }

  // light mode: needs 60 s of steady light/dark to avoid clouds or headlights
  if (!autoLight) { brightSince = darkSince = 0; return; }
  if (ldrValue > ldrOpen) { if (!brightSince) brightSince = millis(); } else brightSince = 0;
  if (ldrValue < ldrClose) { if (!darkSince) darkSince = millis(); } else darkSince = 0;
  if (brightSince && millis() - brightSince > 60000 && percentOpen() < 100 && position == target) moveToPercent(100);
  if (darkSince && millis() - darkSince > 60000 && percentOpen() > 0 && position == target) moveToPercent(0);
}

// ---------- OLED ----------
void drawOled() {
  static unsigned long last = 0;
  // refresh slower while the motor runs so the I2C transfer does not slow the stepping
  if (millis() - last < (position == target ? 300UL : 1000UL)) return;
  last = millis();
  oled.clearDisplay();
  oled.setTextSize(1); oled.setCursor(0, 0);
  oled.print("Curtain ");
  oled.print(position == target ? (percentOpen() == 0 ? "CLOSED" : (percentOpen() == 100 ? "OPEN" : "STOP")) : (target > position ? "OPENING" : "CLOSING"));
  oled.setTextSize(2); oled.setCursor(0, 14); oled.print(percentOpen()); oled.print("%");
  oled.drawRect(60, 16, 66, 12, SSD1306_WHITE);
  oled.fillRect(62, 18, percentOpen() * 62 / 100, 8, SSD1306_WHITE);
  oled.setTextSize(1); oled.setCursor(0, 36);
  oled.print("Light "); oled.print(ldrValue); oled.print(autoLight ? " AUTO" : " man");
  oled.setCursor(0, 46);
  struct tm t;
  if (getLocalTime(&t, 5)) { char b[6]; strftime(b, 6, "%H:%M", &t); oled.print(b); }
  if (!homed) oled.print(" NO HOME!");
  oled.setCursor(0, 56);
  oled.print(WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString() : String("Wi-Fi offline"));
  oled.display();
}

// ---------- web page ----------
String hhmm(int m) { if (m < 0) return ""; char b[6]; sprintf(b, "%02d:%02d", m / 60, m % 60); return b; }
int parseHHMM(const String& s) {
  if (s.length() < 4) return -1;
  int c = s.indexOf(':'); if (c < 0) return -1;
  return constrain(s.substring(0, c).toInt(), 0, 23) * 60 + constrain(s.substring(c + 1).toInt(), 0, 59);
}

const char PAGE[] PROGMEM = R"HTML(<!doctype html><html><head><meta name=viewport content="width=device-width,initial-scale=1">
<title>Smart Curtain</title><style>body{font-family:Arial;max-width:420px;margin:auto;padding:12px;background:#f3f6fb}
.c{background:#fff;border-radius:12px;padding:14px;margin:10px 0;box-shadow:0 1px 4px #0002}button{font-size:18px;padding:10px 16px;margin:4px;border:0;border-radius:8px;background:#1565c0;color:#fff}
#p{font-size:42px;font-weight:bold}input[type=range]{width:100%}</style></head><body>
<h2>ESP32 Smart Curtain</h2><div class=c><div id=p>--%</div><div id=s></div>
<button onclick="go('/move?pct=100')">Open</button><button onclick="go('/stop')">Stop</button><button onclick="go('/move?pct=0')">Close</button>
<p>Set position: <input type=range id=r min=0 max=100 onchange="go('/move?pct='+this.value)"></p></div>
<div class=c><b>Automatic</b><p><label><input type=checkbox id=a onchange="go('/set?auto='+(this.checked?1:0))"> Open with daylight, close at dark</label></p>
<p>Light sensor: <span id=l></span></p>
<p>Open at <input type=time id=o> Close at <input type=time id=cl> <button onclick="go('/set?open='+o.value+'&close='+cl.value)">Save</button></p><small>Clear a time box to switch that timer off.</small></div>
<script>function go(u){fetch(u).then(upd)}
function upd(){fetch('/data').then(r=>r.json()).then(d=>{p.textContent=d.pct+'%';s.textContent=d.state+(d.homed?'':' (not homed!)');l.textContent=d.ldr;
a.checked=d.auto;if(document.activeElement!=r)r.value=d.pct;if(document.activeElement!=o)o.value=d.open;if(document.activeElement!=cl)cl.value=d.close;})}
setInterval(upd,1000);upd();</script></body></html>)HTML";

void handleData() {
  String st = position == target ? "Stopped" : (target > position ? "Opening" : "Closing");
  String j = "{\"pct\":" + String(percentOpen()) + ",\"state\":\"" + st + "\",\"ldr\":" + String(ldrValue) +
             ",\"auto\":" + (autoLight ? "true" : "false") + ",\"homed\":" + (homed ? "true" : "false") +
             ",\"open\":\"" + hhmm(openMin) + "\",\"close\":\"" + hhmm(closeMin) + "\"}";
  server.send(200, "application/json", j);
}

void setupWeb() {
  server.on("/", []() { server.send_P(200, "text/html", PAGE); });
  server.on("/data", handleData);
  server.on("/move", []() { moveToPercent(server.arg("pct").toInt()); server.send(200, "text/plain", "OK"); });
  server.on("/stop", []() { stopMotor(); server.send(200, "text/plain", "OK"); });
  server.on("/set", []() {
    if (server.hasArg("auto")) { autoLight = server.arg("auto") == "1"; prefs.putBool("auto", autoLight); }
    if (server.hasArg("open"))  { openMin = parseHHMM(server.arg("open"));   prefs.putInt("open", openMin); }
    if (server.hasArg("close")) { closeMin = parseHHMM(server.arg("close")); prefs.putInt("close", closeMin); }
    server.send(200, "text/plain", "OK");
  });
  server.begin();
}

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) pinMode(COIL[i], OUTPUT);
  coilsOff();
  pinMode(PIN_LIMIT, INPUT_PULLUP);
  pinMode(PIN_BUTTON, INPUT_PULLUP);
  analogReadResolution(12);

  Wire.begin(21, 22);
  Wire.setClock(400000);                    // fast I2C = shorter OLED updates
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
  oled.setTextColor(SSD1306_WHITE);

  prefs.begin("curtain", false);
  travel   = prefs.getLong("travel", TRAVEL_DEFAULT);
  autoLight = prefs.getBool("auto", false);
  openMin  = prefs.getInt("open", openMin);
  closeMin = prefs.getInt("close", closeMin);

  homeCurtain();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  unsigned long t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) delay(250);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("IP: "); Serial.println(WiFi.localIP());
    MDNS.begin("curtain");                    // http://curtain.local
    configTzTime(TZ_INFO, "pool.ntp.org", "time.google.com");
  } else Serial.println("Wi-Fi offline - button and light mode still work");
  setupWeb();
}

void loop() {
  runMotor();
  server.handleClient();
  checkButton();
  checkAuto();
  drawOled();
}

Calibration and Testing

  • Open the Serial Monitor at 115200 baud. At power-up the motor turns toward the closed side until the limit switch clicks, then prints Homed at limit switch and the IP address.
  • Open http://curtain.local (or the IP shown on the OLED) on a phone on the same Wi-Fi. Press Open and count how far the curtain travels. If it stops short or runs too far, change TRAVEL_DEFAULT (4096 half-steps = one output turn) and upload again.
  • Cover the LDR with your hand and watch the light value on the page. Note the reading in normal daylight and at dusk, then set ldrOpen and ldrClose between them.
  • Enter open and close times on the page and press Save. Clear a time box and save to switch that timer off.
  • If the motor misses steps or buzzes, raise STEP_US to 1500–2000 µs. Lower values move faster but give less torque.

Troubleshooting

ProblemFix
Motor hums but does not turnThe coil order is wrong or a wire is loose. Check IN1–IN4 go to GPIO26, 25, 33, 32 in that order, and that the 5-pin plug is fully seated. Increase STEP_US if the load is heavy.
ULN2003 LEDs blink but the ESP32 resetsThe supply is too weak. Use a 5 V 2 A adapter, keep the grounds joined, and add a 470 µF capacitor across the 5 V rail.
“Limit switch not found!” at bootHoming ran for a full travel without a switch press. Check the switch is wired COM to GPIO13 and NO to GND, and that the motor turns toward the closed side (swap the coil wires if not).
Curtain closes but never opensThe position is clamped at 0 when the switch is pressed. If the switch stays pressed, move it so the curtain releases it after a few millimetres.
Light mode never triggersThe LDR reading stays between the two levels. Read the value on the web page and adjust ldrOpen and ldrClose. Remember there is a 60-second delay on purpose.
Timers run at the wrong timeThe clock comes from NTP, so Wi-Fi is needed after each power-up. Change TZ_INFO if you are not in India (for example “GMT0” for UK winter time).
Web page does not openUse the IP address on the OLED instead of curtain.local (some Android phones do not support mDNS), and use a 2.4 GHz network.

Ideas to Extend

  • Swap the 28BYJ-48 for a NEMA 17 stepper and an A4988 driver (same STEP/DIR idea) for heavy blackout curtains.
  • Add a second limit switch at the open end so the travel length is measured automatically.
  • Add a DHT22 and close the curtain on hot afternoons to keep the room cool.

ESP32 BLE Relay Switch with Push Button & Phone Control (No Wi-Fi Needed)

ESP32 BLE relay switch on a breadboard with relay module, push button, lamp and a phone BLE terminal app showing RELAY:ON

Switch a lamp or any small load from your phone with an ESP32 BLE relay switch: no Wi-Fi router or internet needed, a local push button for manual control, and live ON/OFF feedback in a free BLE terminal app.

  • DifficultyBeginner
  • Build time1–2 hours
  • Board / MCUESP32 DevKit V1
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Most phone-controlled switches need a Wi-Fi router, an internet connection and a cloud app. Sometimes you just want to switch a lamp, a fan or a pump from your phone while you are standing in the same room, even where there is no Wi-Fi at all. This ESP32 BLE relay switch uses the Bluetooth Low Energy radio that is already built into every ESP32, so the phone talks directly to the board.

You send simple text commands such as ON, OFF or T (toggle) from a free BLE terminal app, and the ESP32 replies with the new state, so you always know whether the load is really on. A push button next to the relay works as a normal manual switch, and the phone is updated when you press it. It is a great first BLE project and a building block for bigger home automation builds.

ESP32 BLE relay switch on a breadboard with relay module, push button, lamp and a phone BLE terminal app showing RELAY:ON

How It Works

  • BLE UART service: the ESP32 advertises as APH-BLE-Relay and offers the Nordic UART Service (NUS). This is a standard “serial port over BLE” that most terminal apps understand, so you do not need to build your own app.
  • RX characteristic: text written by the phone lands in the RX characteristic. The callback cleans it up (trims spaces, converts to upper case) and hands it to loop(), so the relay is never switched from inside the Bluetooth task.
  • TX characteristic: after every change the ESP32 sends RELAY:ON or RELAY:OFF as a notification. Send S at any time to ask for the current state.
  • Push button: the button on GPIO27 uses the internal pull-up. A 50 ms debounce stops one press from toggling the relay twice.
  • Connection LED: the on-board blue LED on GPIO2 is on while a phone is connected. When the phone disconnects, the ESP32 starts advertising again so you can reconnect without resetting it.
  • Safe start: the relay is always OFF when the board powers up or resets.

Components Required

  • ESP32 DevKit V1 (ESP-WROOM-32) – 1
  • 5V single-channel relay module (active-LOW input, with optocoupler) – 1
  • Tactile push button – 1
  • Breadboard and jumper wires – 1 set
  • 5V USB power supply or USB cable – 1
  • Small lamp, fan or DC load for testing (use a 12V DC load first) – 1
  • Android or iPhone with a BLE terminal app (Serial Bluetooth Terminal / Bluefruit Connect) – 1

Wiring Table

Module pinESP32 pinNotes
Relay VCCVIN (5V from USB)Relay coil needs 5V
Relay GNDGNDCommon ground
Relay INGPIO26Active-LOW: LOW = relay ON (change RELAY_ACTIVE_LOW if yours is active-HIGH)
Push button leg 1GPIO27Internal pull-up, no resistor needed
Push button leg 2GNDPressed = LOW
Status LEDGPIO2 (on-board)Already on the DevKit board
Relay COM / NOSupply + / loadLoad ON when relay is energised

Connection Diagram

The illustration above shows a typical breadboard layout and is a layout guide only. Follow the pin-accurate drawing below, which matches the wiring table and the code.

ESP32 BLE Relay Switch – Pin-Accurate Wiring ESP32 DEVKIT V1 VIN (5V) Relay module VCC GND Relay GND and one leg of push button GPIO26 Relay module IN (LOW = relay ON) GPIO27 Other leg of push button (internal pull-up) GPIO2 On-board blue LED = phone connected Relay contacts: COM to supply live/+, NO to the load. The load is OFF at power-up and turns ON when the relay clicks. Power the ESP32 from USB so VIN gives 5V to the relay coil. Signals from GPIO26 are 3.3V; most optocoupler relay modules accept it. Test with a 12V DC load first. Mains (230V) wiring must be enclosed and done by a qualified person.
Pin-accurate connection diagram for the ESP32 BLE relay switch.

Code

Install the esp32 board package (version 3.x) in the Arduino IDE. The BLE library is included with it, so no extra library is needed. Select ESP32 Dev Module, choose the correct COM port and upload. The sketch compiles with ESP32 Arduino core 3.3 and uses about 1.1 MB of flash, which fits the default partition scheme.

/*
  ESP32 BLE Relay Switch with Push Button & Status LED
  Arduino Project Hub - https://ardiunoprojecthub.online
  Control one relay from your phone over Bluetooth Low Energy (BLE).
  The ESP32 acts as a "BLE UART" (Nordic UART Service), so any BLE terminal
  app (for example "Serial Bluetooth Terminal" on Android or "Bluefruit Connect"
  on iPhone) can send text commands:
    ON      -> relay ON
    OFF     -> relay OFF
    T       -> toggle relay
    S       -> ask for the current state
  A local push button also toggles the relay, and every change is sent back
  to the phone as a notification ("RELAY:ON" / "RELAY:OFF").
  Board: ESP32 Dev Module (ESP32 Arduino core 3.x, built-in BLE library)
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>

// ----- Pins -----
const int RELAY_PIN  = 26;   // relay module IN
const int BUTTON_PIN = 27;   // push button to GND (internal pull-up)
const int LED_PIN    = 2;    // on-board blue LED = BLE connected
const bool RELAY_ACTIVE_LOW = true;   // most blue relay modules switch ON with LOW

// ----- Nordic UART Service UUIDs (understood by most BLE terminal apps) -----
#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
#define RX_UUID      "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"  // phone -> ESP32
#define TX_UUID      "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"  // ESP32 -> phone

BLECharacteristic *txChar = nullptr;
volatile bool deviceConnected = false;
bool lastConnected = false;
bool relayOn = false;
volatile bool commandWaiting = false;
String pendingCommand = "";

// Drive the relay and remember the state
void setRelay(bool on) {
  relayOn = on;
  bool level = RELAY_ACTIVE_LOW ? !on : on;
  digitalWrite(RELAY_PIN, level ? HIGH : LOW);
  Serial.printf("Relay %s\n", on ? "ON" : "OFF");
}

// Send the current state to the phone (if connected)
void sendState() {
  if (deviceConnected && txChar != nullptr) {
    String msg = relayOn ? "RELAY:ON\n" : "RELAY:OFF\n";
    txChar->setValue(msg.c_str());
    txChar->notify();
  }
}

// Connection events
class ServerCallbacks : public BLEServerCallbacks {
  void onConnect(BLEServer *server) override {
    deviceConnected = true;
  }
  void onDisconnect(BLEServer *server) override {
    deviceConnected = false;
  }
};

// Text written by the phone arrives here
class RxCallbacks : public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *ch) override {
    String value = ch->getValue();   // String in ESP32 core 3.x
    value.trim();
    value.toUpperCase();
    if (value.length() > 0) {
      pendingCommand = value;        // handled in loop(), not inside the BLE task
      commandWaiting = true;
    }
  }
};

void handleCommand(const String &cmd) {
  if (cmd == "ON" || cmd == "1")       setRelay(true);
  else if (cmd == "OFF" || cmd == "0") setRelay(false);
  else if (cmd == "T" || cmd == "TOGGLE") setRelay(!relayOn);
  else if (cmd != "S" && cmd != "STATUS") {
    if (deviceConnected) {
      txChar->setValue("Use ON, OFF, T or S\n");
      txChar->notify();
    }
    return;
  }
  sendState();
}

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  setRelay(false);                    // start with the load OFF

  BLEDevice::init("APH-BLE-Relay");   // name shown in the phone app
  BLEServer *server = BLEDevice::createServer();
  server->setCallbacks(new ServerCallbacks());

  BLEService *service = server->createService(SERVICE_UUID);
  txChar = service->createCharacteristic(TX_UUID, BLECharacteristic::PROPERTY_NOTIFY);
  txChar->addDescriptor(new BLE2902());
  BLECharacteristic *rxChar = service->createCharacteristic(
      RX_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR);
  rxChar->setCallbacks(new RxCallbacks());
  service->start();

  BLEAdvertising *adv = BLEDevice::getAdvertising();
  adv->addServiceUUID(SERVICE_UUID);
  adv->setScanResponse(true);
  BLEDevice::startAdvertising();
  Serial.println("Advertising as APH-BLE-Relay. Connect with a BLE terminal app.");
}

void loop() {
  // 1) Commands from the phone
  if (commandWaiting) {
    commandWaiting = false;
    handleCommand(pendingCommand);
  }

  // 2) Local push button with simple debounce (toggle on press)
  static bool lastButton = HIGH;
  static unsigned long lastChange = 0;
  bool reading = digitalRead(BUTTON_PIN);
  if (reading != lastButton && millis() - lastChange > 50) {
    lastChange = millis();
    lastButton = reading;
    if (reading == LOW) {             // pressed
      setRelay(!relayOn);
      sendState();
    }
  }

  // 3) Connection LED and restart advertising after a disconnect
  digitalWrite(LED_PIN, deviceConnected ? HIGH : LOW);
  if (deviceConnected && !lastConnected) {
    delay(300);                       // let the app subscribe first
    sendState();
  }
  if (!deviceConnected && lastConnected) {
    delay(300);
    BLEDevice::startAdvertising();
    Serial.println("Disconnected - advertising again");
  }
  lastConnected = deviceConnected;
  delay(5);
}

Connecting from Your Phone

  • Android: install Serial Bluetooth Terminal, open Devices → Bluetooth LE, scan and tap APH-BLE-Relay. You do not pair it in the phone’s Bluetooth settings.
  • iPhone: install Bluefruit Connect (or any NUS-compatible app), connect to APH-BLE-Relay and open the UART screen.
  • Type ON and send: the relay clicks and the app shows RELAY:ON. Send OFF, T or S to test the other commands.
  • Tip: in Serial Bluetooth Terminal you can save ON and OFF as macro buttons for one-tap control.

Troubleshooting

ProblemFix
APH-BLE-Relay does not appear in the scanScan from inside the app, not the phone’s Bluetooth settings. Turn on Location on Android (needed for BLE scans) and check the Serial Monitor shows “Advertising”.
Relay works the opposite wayYour module is active-HIGH. Set RELAY_ACTIVE_LOW = false in the code.
Relay clicks but ESP32 resetsThe relay coil is pulling the USB supply down. Use a good 5V 1A supply and a module with an optocoupler, and keep the load wiring away from the ESP32.
Commands are ignoredSend plain text with a newline or nothing after it; the code trims it. Check that the app is writing to the RX characteristic (6E400002…).
No RELAY:ON reply in the appEnable notifications on the TX characteristic (6E400003…). Most terminal apps do this automatically after connecting.
Cannot reconnect after leaving the roomWait 2–3 seconds; the ESP32 restarts advertising after a disconnect. Close and reopen the app if it still shows the old connection.
Upload fails with “Sketch too big”Choose a partition scheme with at least 1.2 MB app space (the default one works) under Tools → Partition Scheme.

Ideas to Extend

  • Add three more relays and commands like R2 ON for a 4-channel BLE switch board.
  • Add an auto-off timer command such as TIMER 30 to switch the load off after 30 minutes.
  • Save the last state in Preferences so the relay returns to it after a power cut.

ESP32 Smart Pet Feeder with Load Cell, Servo, OLED & Web Schedule

ESP32 smart pet feeder with servo-driven kibble hopper, bowl on a load cell with HX711, OLED display, buzzer, button and a phone showing the meal schedule web page

Build an ESP32 smart pet feeder that serves up to four scheduled meals, weighs every portion with a load cell, shows the bowl weight on an OLED and lets you feed or change the schedule from your phone.

  • DifficultyAdvanced
  • Build time5–7 hours
  • Board / MCUESP32 DevKit V1
  • Parts13 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 smart pet feeder feeds your dog or cat on time even when nobody is home. A servo opens a gate under a kibble hopper, and the bowl sits on a load cell, so the ESP32 keeps the gate open until the bowl has gained exactly the grams you asked for. You get up to four meals a day, a small OLED that shows the bowl weight and the next meal, a chime that calls your pet, and a phone web page to change the schedule or press Feed now.

It is a big combination project: Wi-Fi and NTP time, a weighing scale, a motor, a display and a web app all running on one board. Because it measures food by weight instead of by servo time, every portion is the same size no matter how full the hopper is, and it can tell you when the hopper is empty or jammed.

ESP32 smart pet feeder with servo-driven kibble hopper, bowl on a load cell with HX711, OLED display, buzzer, button and a phone showing the meal schedule web page

How It Works

  • Keeping time: after joining your Wi-Fi the ESP32 gets the time from an NTP server and sets it to Indian Standard Time (UTC+5:30). The internal clock keeps running if Wi-Fi drops later.
  • Weighing the bowl: the load cell bends very slightly under the bowl and its four strain gauges change resistance. The HX711 is a 24-bit amplifier and converter that turns this tiny change into a number. The code averages five readings and divides by a calibration factor to get grams. At power-on the empty bowl is tared to 0 g.
  • Closed-loop portions: at meal time the buzzer chimes twice, the servo swings the gate to 80°, and the ESP32 reads the bowl about 10 times a second. As soon as the bowl has gained the set grams (minus 2 g for kibble still falling), the gate closes. A 15 second timeout and a 400 g bowl limit stop it from ever overfilling.
  • Jam and empty hopper alarm: while the gate is open it wiggles by 15° every 2 seconds to break up stuck kibble. If less than 30 percent of the portion arrives, the OLED shows CHECK HOPPER / JAM, the web page turns red and the buzzer beeps every 30 seconds until you press the button.
  • Schedule in flash: the four meal slots (on/off, time and grams) are saved with the ESP32 Preferences library, so a power cut does not erase them. Each meal fires once per day.
  • Web app: open the IP address or http://petfeeder.local on a phone on the same Wi-Fi. The page shows the live bowl weight, next meal and last feed, and has Feed now, Tare scale and a schedule form.
  • Button: a short press feeds one portion (the size of meal 1) and clears the alarm. Holding it for 3 seconds tares the scale; do this with the empty bowl in place.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • MG996R metal-gear servo (or SG90 for a small feeder) – 1
  • 1 kg or 5 kg bar load cell – 1
  • HX711 load cell amplifier module – 1
  • 0.96 inch SSD1306 I2C OLED display (128×64) – 1
  • Active 5V buzzer – 1
  • BC547 NPN transistor and 1 kΩ base resistor – 1 each
  • Push button (feed now / tare) – 1
  • 5V 2A power adapter with DC jack – 1
  • 470 µF 16V electrolytic capacitor (across servo supply) – 1
  • Food hopper (2 L plastic container or cereal dispenser), gate flap or paddle, and a steel bowl – 1 set
  • Two small plates of acrylic or MDF to mount the load cell, M4/M5 screws – 1 set
  • Perfboard or breadboard and jumper wires – 1 set

Wiring Table

Part / pinESP32 pinNotes
HX711 VCC / GND3V3 / GNDKeeps HX711 outputs at 3.3V logic
HX711 DT / SCKGPIO16 / GPIO17
Load cell red / black / white / greenHX711 E+ / E- / A- / A+Swap white and green if weight reads negative
Servo signal (orange)GPIO18Servo power from the 5V 2A supply, not the ESP32 3V3
Servo red / brown5V / GND470 µF capacitor across these two
OLED VCC / GND3V3 / GND
OLED SDA / SCLGPIO21 / GPIO22I2C address 0x3C
BC547 baseGPIO25 through 1 kΩEmitter to GND, collector to buzzer -, buzzer + to 5V
ButtonGPIO27 and GNDInternal pull-up
5V supply +ESP32 VINDo not also power from USB while the servo runs

Connection Diagram

The illustration near the top shows how the parts fit together. It is a layout guide only, so follow the pin-accurate drawing below, which matches the wiring table.

ESP32 Smart Pet Feeder – Pin-Accurate Wiring 5V 2A supply 5V to ESP32 VIN, servo red wire and buzzer + 470 µF capacitor across servo 5V and GND All GND pins joined together HX711 + load cell HX711 VCC to 3V3, GND to GND DT to GPIO16, SCK to GPIO17 Load cell: red E+, black E-, white A-, green A+ MG996R servo Signal (orange) to GPIO18 Red to 5V supply, brown to GND OLED (I2C) VCC to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x3C) Buzzer driver GPIO25 to 1 kΩ to BC547 base Emitter to GND, collector to buzzer – Buzzer + to 5V Button One leg to GPIO27, other leg to GND (internal pull-up)
Pin-accurate connection diagram for the ESP32 smart pet feeder.

Building the Feeder

  • Mount the bar load cell between two plates in a Z shape: one end screwed to the base plate, the other end to the top plate that holds the bowl. Use spacers so the middle of the bar can bend freely and the arrow on it points down.
  • Cut a hole in the bottom of the hopper and fit a hinged flap or a small paddle on the servo horn so 80° opens it and 10° closes it. Test the two angles before you fix anything and change GATE_OPEN and GATE_CLOSED if needed.
  • Place the hopper outlet above the bowl but make sure the hopper and chute never touch the bowl or top plate, or the scale will read wrong.
  • Keep the electronics in a box away from water and the pet, and route all wires so the pet cannot chew them.

Calibrating the Scale

  • Upload the sketch with the empty bowl on the scale. It tares to 0 g at power-on.
  • Put a known weight on the bowl, for example a 200 g packet from the kitchen, and read the grams on the OLED.
  • New factor = current CAL_FACTOR × shown grams ÷ real grams. Put that in the code and upload again. Repeat once to check it reads within 2 g.
  • Run a test feed of 40 g and weigh the bowl on a kitchen scale to confirm.

Code

Install the esp32 by Espressif Systems board package in the Arduino IDE and select ESP32 Dev Module. From the Library Manager install HX711 by Rob Tillaart, ESP32Servo, Adafruit SSD1306 and Adafruit GFX Library. Replace the Wi-Fi placeholders with your own network name and password, then upload.

/*
  ESP32 Smart Pet Feeder with Load Cell, Servo, OLED & Web Schedule
  Arduino Project Hub - https://ardiunoprojecthub.online

  - Up to 4 daily meals, set from a phone web page (saved in flash)
  - Servo opens the hopper gate until the bowl gains the set grams (closed loop)
  - HX711 + load cell weighs the bowl, OLED shows time, bowl weight and next meal
  - Buzzer chime before each meal, jam/empty-hopper alarm
  - Button: short press = feed one portion now, hold 3 s = tare (zero) the scale

  Board: ESP32 Dev Module   Libraries: HX711 (Rob Tillaart), ESP32Servo,
  Adafruit SSD1306, Adafruit GFX
*/
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Preferences.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <ESP32Servo.h>
#include <HX711.h>
#include <time.h>

// ---------- Wi-Fi (replace with your own) ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

// ---------- Pins ----------
const int HX_DT    = 16;
const int HX_SCK   = 17;
const int SERVO_PIN = 18;
const int BUZZER   = 25;   // through BC547
const int BUTTON   = 27;   // to GND, internal pull-up

// ---------- Settings ----------
float CAL_FACTOR = 420.0;        // change after calibration (see post)
const int GATE_CLOSED = 10;      // servo angle with gate closed
const int GATE_OPEN   = 80;      // servo angle with gate open
const unsigned long FEED_TIMEOUT_MS = 15000; // max gate-open time
const float MAX_BOWL_G = 400;    // never feed above this bowl weight

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
Servo gate;
HX711 scale;
WebServer server(80);
Preferences prefs;

struct Meal { bool on; uint8_t h; uint8_t m; uint16_t grams; };
Meal meals[4];
int lastFedDay[4] = {-1, -1, -1, -1};
float bowlG = 0;
String lastFeed = "none";
bool jamAlarm = false;

// ---------- Helpers ----------
void beep(int times, int ms) {
  for (int i = 0; i < times; i++) {
    digitalWrite(BUZZER, HIGH); delay(ms);
    digitalWrite(BUZZER, LOW);  delay(ms);
  }
}

float readBowl() {
  if (!scale.is_ready()) return bowlG;
  float g = scale.get_units(5);
  if (g < 0 && g > -3) g = 0;     // hide tiny negative drift
  return g;
}

void loadMeals() {
  prefs.begin("feeder", true);
  for (int i = 0; i < 4; i++) {
    String k = "m" + String(i);
    meals[i].on    = prefs.getBool((k + "on").c_str(), i < 2);
    meals[i].h     = prefs.getUChar((k + "h").c_str(), i == 0 ? 8 : (i == 1 ? 18 : 12));
    meals[i].m     = prefs.getUChar((k + "m").c_str(), 0);
    meals[i].grams = prefs.getUShort((k + "g").c_str(), 40);
  }
  CAL_FACTOR = prefs.getFloat("cal", CAL_FACTOR);
  prefs.end();
}

void saveMeals() {
  prefs.begin("feeder", false);
  for (int i = 0; i < 4; i++) {
    String k = "m" + String(i);
    prefs.putBool((k + "on").c_str(), meals[i].on);
    prefs.putUChar((k + "h").c_str(), meals[i].h);
    prefs.putUChar((k + "m").c_str(), meals[i].m);
    prefs.putUShort((k + "g").c_str(), meals[i].grams);
  }
  prefs.end();
}

String nowText() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return "--:--";
  char b[6]; sprintf(b, "%02d:%02d", t.tm_hour, t.tm_min);
  return String(b);
}

String nextMealText() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return "no time";
  int nowMin = t.tm_hour * 60 + t.tm_min, best = 9999, idx = -1;
  for (int i = 0; i < 4; i++) {
    if (!meals[i].on) continue;
    int mm = meals[i].h * 60 + meals[i].m;
    int diff = (mm - nowMin + 1440) % 1440;
    if (diff == 0) diff = 1440;
    if (diff < best) { best = diff; idx = i; }
  }
  if (idx < 0) return "none";
  char b[16]; sprintf(b, "%02d:%02d %dg", meals[idx].h, meals[idx].m, meals[idx].grams);
  return String(b);
}

// ---------- Feeding (closed loop on bowl weight) ----------
bool feed(uint16_t grams) {
  float start = readBowl();
  if (start >= MAX_BOWL_G) return true;          // bowl already full
  float target = min(start + grams, MAX_BOWL_G);
  beep(2, 120);                                   // dinner chime
  gate.write(GATE_OPEN);
  unsigned long t0 = millis();
  float g = start;
  while (millis() - t0 < FEED_TIMEOUT_MS) {
    g = readBowl();
    if (g >= target - 2) break;                   // 2 g allowance for falling kibble
    // wiggle the gate every 2 s to clear a jam
    if (((millis() - t0) / 2000) % 2 == 1) gate.write(GATE_OPEN - 15); else gate.write(GATE_OPEN);
    delay(50);
  }
  gate.write(GATE_CLOSED);
  delay(800);
  bowlG = readBowl();
  float added = bowlG - start;
  lastFeed = nowText() + " +" + String(added, 0) + " g";
  Serial.printf("Fed %.0f g (target %u g)\n", added, grams);
  jamAlarm = (added < grams * 0.3);               // little food came out: hopper empty or jammed
  return !jamAlarm;
}

void checkSchedule() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return;
  for (int i = 0; i < 4; i++) {
    if (meals[i].on && t.tm_hour == meals[i].h && t.tm_min == meals[i].m && lastFedDay[i] != t.tm_yday) {
      lastFedDay[i] = t.tm_yday;
      feed(meals[i].grams);
    }
  }
}

// ---------- Display ----------
void drawOled() {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(1); oled.setCursor(0, 0);
  oled.print(nowText()); oled.print("  ");
  oled.print(WiFi.status() == WL_CONNECTED ? "WiFi OK" : "No WiFi");
  oled.setTextSize(2); oled.setCursor(0, 14);
  oled.print(bowlG, 0); oled.print(" g");
  oled.setTextSize(1); oled.setCursor(0, 36);
  oled.print("Next: "); oled.print(nextMealText());
  oled.setCursor(0, 48);
  if (jamAlarm) oled.print("CHECK HOPPER / JAM!");
  else { oled.print("Last: "); oled.print(lastFeed); }
  oled.display();
}

// ---------- Web page ----------
const char PAGE[] PROGMEM = R"HTML(<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pet Feeder</title><style>body{font-family:Arial;margin:16px;background:#f4f7f7}
.c{background:#fff;border-radius:10px;padding:14px;margin-bottom:12px;box-shadow:0 1px 4px #0002}
h2{margin:0 0 8px;color:#00796b}.big{font-size:32px;font-weight:bold}
button{background:#ef6c00;color:#fff;border:0;border-radius:8px;padding:10px 16px;font-size:16px;margin:4px 4px 0 0}
input{width:70px;padding:4px}.row{margin:6px 0}</style></head><body>
<div class="c"><h2>Bowl</h2><div class="big" id="w">--</div>
<div id="info"></div>
<button onclick="act('/feed')">Feed now</button><button onclick="act('/tare')">Tare scale</button></div>
<div class="c"><h2>Meal schedule</h2><form id="f"></form><button onclick="save()">Save schedule</button></div>
<script>
function act(u){fetch(u,{method:'POST'}).then(r=>r.text()).then(t=>alert(t))}
function load(){fetch('/data').then(r=>r.json()).then(d=>{
 w.innerHTML=d.bowl+' g';info.innerHTML='Time '+d.time+'<br>Next meal '+d.next+'<br>Last feed '+d.last+(d.jam?'<br><b style="color:red">Check hopper or jam!</b>':'');
 if(!f.dataset.done){let h='';d.meals.forEach((m,i)=>{h+=`<div class="row"><input type="checkbox" id="on${i}" ${m.on?'checked':''}> Meal ${i+1}
 <input type="time" id="t${i}" value="${String(m.h).padStart(2,'0')}:${String(m.m).padStart(2,'0')}"> <input type="number" id="g${i}" min="5" max="200" value="${m.g}"> g</div>`});
 f.innerHTML=h;f.dataset.done=1}})}
function save(){let q=[];for(let i=0;i<4;i++){let t=document.getElementById('t'+i).value.split(':');
 q.push(`on${i}=${document.getElementById('on'+i).checked?1:0}&h${i}=${t[0]}&m${i}=${t[1]}&g${i}=${document.getElementById('g'+i).value}`)}
 fetch('/save?'+q.join('&'),{method:'POST'}).then(r=>r.text()).then(t=>alert(t))}
load();setInterval(load,3000);
</script></body></html>)HTML";

void handleData() {
  String j = "{\"bowl\":" + String(bowlG, 0) + ",\"time\":\"" + nowText() + "\",\"next\":\"" + nextMealText() +
             "\",\"last\":\"" + lastFeed + "\",\"jam\":" + (jamAlarm ? "true" : "false") + ",\"meals\":[";
  for (int i = 0; i < 4; i++) {
    j += "{\"on\":" + String(meals[i].on ? "true" : "false") + ",\"h\":" + meals[i].h + ",\"m\":" + meals[i].m + ",\"g\":" + meals[i].grams + "}";
    if (i < 3) j += ",";
  }
  j += "]}";
  server.send(200, "application/json", j);
}

void handleSave() {
  for (int i = 0; i < 4; i++) {
    String s = String(i);
    if (!server.hasArg("h" + s)) continue;
    meals[i].on = server.arg("on" + s) == "1";
    meals[i].h = constrain(server.arg("h" + s).toInt(), 0, 23);
    meals[i].m = constrain(server.arg("m" + s).toInt(), 0, 59);
    meals[i].grams = constrain(server.arg("g" + s).toInt(), 5, 200);
  }
  saveMeals();
  server.send(200, "text/plain", "Schedule saved");
}

void setup() {
  Serial.begin(115200);
  pinMode(BUZZER, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  gate.setPeriodHertz(50);
  gate.attach(SERVO_PIN, 500, 2400);
  gate.write(GATE_CLOSED);

  Wire.begin(21, 22);
  oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
  oled.setCursor(0, 0); oled.print("Pet feeder starting"); oled.display();

  loadMeals();
  scale.begin(HX_DT, HX_SCK);
  scale.set_scale(CAL_FACTOR);
  scale.tare(20);   // keep the EMPTY bowl on the scale at power-on

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  unsigned long t0 = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(300);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Open http://"); Serial.println(WiFi.localIP());
    MDNS.begin("petfeeder");
  }
  configTime(19800, 0, "pool.ntp.org", "time.google.com"); // IST = UTC+5:30

  server.on("/", []() { server.send_P(200, "text/html", PAGE); });
  server.on("/data", handleData);
  server.on("/save", HTTP_POST, handleSave);
  server.on("/feed", HTTP_POST, []() {
    server.send(200, "text/plain", "Feeding one portion");
    feed(meals[0].grams);
  });
  server.on("/tare", HTTP_POST, []() { scale.tare(20); server.send(200, "text/plain", "Scale set to zero"); });
  server.begin();
  beep(1, 80);
}

unsigned long lastUi = 0, lastAlarm = 0;

void loop() {
  server.handleClient();

  // Button: short press feeds, 3 s hold tares
  if (digitalRead(BUTTON) == LOW) {
    unsigned long t0 = millis();
    while (digitalRead(BUTTON) == LOW && millis() - t0 < 3000) delay(10);
    if (millis() - t0 >= 3000) { scale.tare(20); beep(3, 60); }
    else { jamAlarm = false; feed(meals[0].grams); }
    while (digitalRead(BUTTON) == LOW) delay(10);
  }

  if (millis() - lastUi > 1000) {
    lastUi = millis();
    bowlG = readBowl();
    checkSchedule();
    drawOled();
  }

  if (jamAlarm && millis() - lastAlarm > 30000) {  // remind every 30 s
    lastAlarm = millis();
    beep(3, 200);
  }
}

Testing

  • Open the Serial Monitor at 115200 baud and note the IP address after “Open http://”.
  • Check that the OLED shows the correct time within a minute of boot.
  • Press the button once and check that the gate opens, closes when about 40 g has dropped, and the serial line shows the grams fed.
  • Set a meal two minutes ahead on the web page, save it and wait for the chime and feed.
  • Empty the hopper and press Feed now to check the jam alarm.

Troubleshooting

ProblemFix
ESP32 resets when the servo movesThe servo is pulling too much current. Use a 5V 2A supply, add the 470 µF capacitor, and keep the servo off the ESP32 3V3 pin.
Weight reads negative or does not changeSwap the load cell white and green wires, check that the bar is mounted with room to bend, and make sure nothing touches the top plate.
Weight drifts slowlyLet the HX711 warm up for a few minutes, keep the load cell wires short and twisted, and tare again with the empty bowl.
Portions are too bigKibble keeps falling after the gate closes. Raise the 2 g allowance in feed() or make the outlet smaller.
Time shows –:–The ESP32 has not reached the NTP server. Check the Wi-Fi name and password and that the router has internet.
Jam alarm with a full hopperLarge kibble is blocking the outlet. Make the hole bigger or increase GATE_OPEN.

Ideas to Extend

  • Add an IR break-beam sensor in the hopper to warn when food is low before it runs out.
  • Send a phone notification with ntfy after each meal with the grams eaten.
  • Weigh the bowl before the next meal to log how much your pet actually ate each day.

ESP32 Smart Dustbin with Touchless Lid & Fill-Level Web Page

ESP32 smart dustbin with a servo-opened lid, two HC-SR04 ultrasonic sensors and a phone showing the fill level web page

Build a touchless ESP32 smart dustbin: wave your hand and the servo opens the lid, while a second ultrasonic sensor shows how full the bin is on a Wi-Fi web page.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUESP32 DevKit V1
  • Parts8 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 smart dustbin opens its lid by itself when you bring your hand close, so you never have to touch a dirty lid. A second ultrasonic sensor inside the lid measures how full the bin is, and the ESP32 shows that level on a simple web page you can open on any phone connected to your Wi-Fi.

It is a good intermediate project because it combines two sensors, a servo, careful 5V to 3.3V level shifting and a small web server. It is useful in a kitchen, office, clinic or school, and the fill-level page tells you when the bin needs emptying before it overflows.

ESP32 smart dustbin with a servo-opened lid, two HC-SR04 ultrasonic sensors and a phone showing the fill level web page

How It Works

  • Hand detection: the lid sensor faces forward and is read about ten times a second. When something is closer than 20 cm, the ESP32 turns the servo to the open angle. The lid stays open for 4 seconds after your hand moves away, then closes.
  • Fill level: the second sensor faces down into the bin. It measures the distance to the top of the rubbish. An empty 30 cm deep bin reads about 30 cm and a full one about 4 cm, and the code turns that into 0 to 100 percent. It takes the middle of five readings to ignore odd echoes, and it only measures while the lid is closed so the sensor is in a fixed position.
  • Level shifting: the HC-SR04 runs on 5V and its ECHO pin outputs 5V, which is too much for an ESP32 pin. A 1 kΩ and 2 kΩ divider on each ECHO line brings it down to about 3.3V. The TRIG pin is fine with the ESP32’s 3.3V signal.
  • Servo signal: ESP32 core 3.x has a built-in PWM unit (LEDC). The sketch sets it to 50 Hz and sends a 500 to 2400 µs pulse, which is all a hobby servo needs, so no servo library is required.
  • Web page: the ESP32 joins your Wi-Fi and serves a page at its IP address or http://smartbin.local. The page asks /data every 2 seconds for the fill percent, lid state and open count, and has an Open lid button that calls /open.
  • Full warning: at 85 percent the on-board LED turns on and the page bar turns red with a message to empty the bin.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • HC-SR04 ultrasonic sensor – 2 (one for the hand, one for the fill level)
  • MG90S metal-gear servo (or SG90 for a very light lid) – 1
  • 1 kΩ resistor – 2 and 2 kΩ resistor – 2 (echo voltage dividers)
  • 470 µF 10V electrolytic capacitor (across servo supply) – 1
  • 5V 2A power adapter with DC jack or USB breakout – 1
  • Dustbin with a hinged flap lid (5 to 10 litre) – 1
  • Breadboard or small perfboard, jumper wires, double-sided tape and a small L-bracket for the servo

Wiring Table

Part / pinESP32 pinNotes
Lid HC-SR04 VCC / GNDVIN (5V) / GNDSensor needs 5V
Lid HC-SR04 TRIGGPIO53.3V trigger works fine
Lid HC-SR04 ECHOGPIO18 through 1 kΩ, 2 kΩ to GNDVoltage divider, never connect ECHO directly
Fill HC-SR04 VCC / GNDVIN (5V) / GNDMount under the lid facing down
Fill HC-SR04 TRIGGPIO19
Fill HC-SR04 ECHOGPIO23 through 1 kΩ, 2 kΩ to GNDVoltage divider
Servo orange (signal)GPIO1350 Hz LEDC PWM
Servo red / brown+5V supply / GNDPower from the 5V 2A adapter, not the 3V3 pin
470 µF capacitorAcross servo +5V and GNDStops ESP32 brownout resets
Full LEDGPIO2 (on-board)No wiring needed

Connection Diagram

The illustration at the top shows how the parts sit on the bin. It is a layout guide only. Follow the pin-accurate drawing below, which matches the wiring table exactly.

ESP32 Smart Dustbin – Pin-Accurate Wiring 5V 2A supply +5V to ESP32 VIN, both HC-SR04 VCC pins and servo red wire GND to ESP32 GND, both HC-SR04 GND pins and servo brown wire 470 µF capacitor across servo +5V and GND (long leg to +5V) Lid sensor (hand) TRIG to GPIO5 ECHO to 1 kΩ to GPIO18 2 kΩ from GPIO18 to GND (5V echo becomes 3.3V) Fill sensor (inside) TRIG to GPIO19 ECHO to 1 kΩ to GPIO23 2 kΩ from GPIO23 to GND Servo (lid) Orange (signal) wire to GPIO13 Red to +5V supply, brown to GND Full LED On-board LED on GPIO2: on when the bin is 85% full or more
Pin-accurate connection diagram for the ESP32 smart dustbin.

Mechanical Setup

  • Fix the servo at the back of the bin with an L-bracket so its horn pushes the lid up from the hinge side. A stiff wire or a small 3D-printed arm between the horn and the lid works well.
  • Stick the lid sensor on the front edge of the lid or bin body, facing forward and slightly upward, so it sees a hand but not people walking past.
  • Stick the fill sensor under the lid in the centre, facing straight down. Measure the distance from its face to the bin floor and put that number in BIN_DEPTH_CM.
  • Keep the ESP32 and wiring in a small box outside the bin, away from moisture.

Code

Install the esp32 by Espressif Systems board package version 3.x in the Arduino IDE (Boards Manager) and choose ESP32 Dev Module. The Wi-Fi, web server and mDNS libraries come with the board package, so nothing else is needed. Replace the Wi-Fi placeholders with your own network name and password, set BIN_DEPTH_CM for your bin, then upload.

/*
  ESP32 Smart Dustbin with Touchless Lid & Fill-Level Web Page
  ardiunoprojecthub.online - Project 52

  - HC-SR04 #1 (on the front of the lid) looks for a hand. When something
    comes closer than OPEN_CM, the servo opens the lid and keeps it open
    for LID_OPEN_MS after the hand goes away.
  - HC-SR04 #2 (under the lid, facing down) measures how full the bin is.
    It is read only while the lid is closed, so the reading is stable.
  - The ESP32 joins your Wi-Fi and serves a web page with a fill gauge,
    lid state, open counter and an "Open lid" button.
  - The on-board LED turns on when the bin is FULL_PERCENT full or more.

  Wiring (ESP32 DevKit V1, 30-pin):
    Lid sensor  : VCC -> VIN (5V), GND -> GND, TRIG -> GPIO5,
                  ECHO -> 1k -> GPIO18, with 2k from GPIO18 to GND
    Fill sensor : VCC -> VIN (5V), GND -> GND, TRIG -> GPIO19,
                  ECHO -> 1k -> GPIO23, with 2k from GPIO23 to GND
    Servo       : red -> 5V supply, brown -> GND, orange (signal) -> GPIO13
    Full LED    : on-board LED on GPIO2
    Power the board and servo from a 5V 2A supply, grounds common.

  No extra libraries are needed with ESP32 core 3.x: the servo pulse is
  made with the built-in LEDC PWM (ledcAttach / ledcWrite).
*/
#include <WiFi.h>
#include <WebServer.h>
#include <ESPmDNS.h>

// ---- Wi-Fi (replace the placeholders) ----
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

// ---- Pins ----
#define LID_TRIG   5
#define LID_ECHO   18
#define FILL_TRIG  19
#define FILL_ECHO  23
#define SERVO_PIN  13
#define LED_PIN    2

// ---- Settings ----
const float OPEN_CM        = 20.0;   // hand distance that opens the lid
const unsigned long LID_OPEN_MS = 4000; // stay open this long after the hand leaves
const float BIN_DEPTH_CM   = 30.0;   // distance from fill sensor to the bin floor (empty bin)
const float FULL_GAP_CM    = 4.0;    // distance at which we call the bin 100 % full
const int   FULL_PERCENT   = 85;     // LED and web warning above this
const int   ANGLE_CLOSED   = 0;      // adjust to your lid hinge
const int   ANGLE_OPEN     = 100;

// Servo PWM: 50 Hz, 14-bit resolution (20 ms period = 16384 steps)
const int SERVO_MIN_US = 500;
const int SERVO_MAX_US = 2400;

WebServer server(80);

bool lidOpen = false;
unsigned long lastHandMs = 0;
unsigned long lastFillMs = 0;
int fillPercent = 0;
float fillDistance = BIN_DEPTH_CM;
unsigned long openCount = 0;

void servoWrite(int angle) {
  angle = constrain(angle, 0, 180);
  int us = map(angle, 0, 180, SERVO_MIN_US, SERVO_MAX_US);
  uint32_t duty = (uint32_t)us * 16384UL / 20000UL;
  ledcWrite(SERVO_PIN, duty);
}

// Returns distance in cm, or -1 if no echo within ~4 m
float readDistance(int trig, int echo) {
  digitalWrite(trig, LOW);
  delayMicroseconds(3);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  unsigned long t = pulseIn(echo, HIGH, 25000UL);
  if (t == 0) return -1;
  return t * 0.0343 / 2.0;
}

// Median of 5 readings to ignore odd echoes
float readMedian(int trig, int echo) {
  float v[5];
  int n = 0;
  for (int i = 0; i < 5; i++) {
    float d = readDistance(trig, echo);
    if (d > 0) v[n++] = d;
    delay(30);
  }
  if (n == 0) return -1;
  for (int i = 1; i < n; i++) {          // simple insertion sort
    float k = v[i]; int j = i - 1;
    while (j >= 0 && v[j] > k) { v[j + 1] = v[j]; j--; }
    v[j + 1] = k;
  }
  return v[n / 2];
}

void openLid() {
  if (!lidOpen) {
    servoWrite(ANGLE_OPEN);
    lidOpen = true;
    openCount++;
    Serial.println("Lid opened");
  }
  lastHandMs = millis();
}

void closeLid() {
  servoWrite(ANGLE_CLOSED);
  lidOpen = false;
  Serial.println("Lid closed");
}

void updateFill() {
  float d = readMedian(FILL_TRIG, FILL_ECHO);
  if (d < 0) return;                      // keep the last good value
  fillDistance = d;
  float pct = (BIN_DEPTH_CM - d) * 100.0 / (BIN_DEPTH_CM - FULL_GAP_CM);
  fillPercent = constrain((int)(pct + 0.5), 0, 100);
  digitalWrite(LED_PIN, fillPercent >= FULL_PERCENT ? HIGH : LOW);
  Serial.printf("Fill: %.1f cm -> %d %%\n", d, fillPercent);
}

// ---- Web page (stored in flash) ----
const char PAGE[] PROGMEM = R"HTML(
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Smart Dustbin</title>
<style>
body{font-family:Arial,sans-serif;text-align:center;background:#f4f6f8;margin:0;padding:20px}
.card{background:#fff;max-width:340px;margin:auto;border-radius:14px;padding:20px;box-shadow:0 2px 8px #0002}
.bar{height:26px;background:#e0e0e0;border-radius:13px;overflow:hidden;margin:12px 0}
#fill{height:100%;width:0;background:#43a047;transition:width .5s}
#pct{font-size:48px;font-weight:bold;margin:6px 0}
button{font-size:18px;padding:10px 24px;border:0;border-radius:8px;background:#1565c0;color:#fff}
.warn{color:#c62828;font-weight:bold}
</style></head><body><div class="card">
<h2>Smart Dustbin</h2>
<div id="pct">--%</div>
<div class="bar"><div id="fill"></div></div>
<p id="state">Loading...</p>
<p>Lid: <b id="lid">-</b> &middot; Opened <b id="count">0</b> times</p>
<button onclick="fetch('/open')">Open lid</button>
</div>
<script>
function tick(){fetch('/data').then(r=>r.json()).then(d=>{
 document.getElementById('pct').textContent=d.fill+'%';
 var f=document.getElementById('fill');f.style.width=d.fill+'%';
 f.style.background=d.fill>=d.full?'#c62828':(d.fill>=50?'#fb8c00':'#43a047');
 var s=document.getElementById('state');
 if(d.fill>=d.full){s.textContent='Bin is full, please empty it';s.className='warn';}
 else{s.textContent='Space left: about '+(100-d.fill)+'%';s.className='';}
 document.getElementById('lid').textContent=d.lid?'Open':'Closed';
 document.getElementById('count').textContent=d.opens;
}).catch(()=>{});}
tick();setInterval(tick,2000);
</script></body></html>
)HTML";

void handleRoot() { server.send_P(200, "text/html", PAGE); }

void handleData() {
  char json[96];
  snprintf(json, sizeof(json), "{\"fill\":%d,\"dist\":%.1f,\"lid\":%s,\"opens\":%lu,\"full\":%d}",
           fillPercent, fillDistance, lidOpen ? "true" : "false", openCount, FULL_PERCENT);
  server.send(200, "application/json", json);
}

void handleOpen() {
  openLid();
  server.send(200, "text/plain", "OK");
}

void setup() {
  Serial.begin(115200);
  pinMode(LID_TRIG, OUTPUT);
  pinMode(FILL_TRIG, OUTPUT);
  pinMode(LID_ECHO, INPUT);
  pinMode(FILL_ECHO, INPUT);
  pinMode(LED_PIN, OUTPUT);

  ledcAttach(SERVO_PIN, 50, 14);          // ESP32 core 3.x API
  closeLid();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 20000) {
    delay(400);
    Serial.print(".");
  }
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("\nOpen http://");
    Serial.println(WiFi.localIP());
    if (MDNS.begin("smartbin")) Serial.println("or http://smartbin.local");
  } else {
    Serial.println("\nWi-Fi not connected: the lid still works offline");
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/open", handleOpen);
  server.begin();
  updateFill();
}

void loop() {
  server.handleClient();

  // Hand detection, about 10 times a second
  static unsigned long lastLid = 0;
  if (millis() - lastLid > 100) {
    lastLid = millis();
    float d = readDistance(LID_TRIG, LID_ECHO);
    if (d > 2 && d < OPEN_CM) openLid();
  }

  // Close after the hand has gone for LID_OPEN_MS
  if (lidOpen && millis() - lastHandMs > LID_OPEN_MS) {
    closeLid();
    lastFillMs = millis() - 4000;         // measure fill 1 s after closing
  }

  // Fill level every 5 s, only when the lid is closed
  if (!lidOpen && millis() - lastFillMs > 5000) {
    lastFillMs = millis();
    updateFill();
  }
}

Testing

  • Open the Serial Monitor at 115200 baud and wait for “Open http://192.168.x.x”.
  • Wave your hand 10 to 15 cm in front of the lid sensor: the lid should open and close again about 4 seconds after you move away.
  • With the bin empty, check that the Serial Monitor shows a fill distance close to BIN_DEPTH_CM and about 0 percent.
  • Put a box or a stack of books inside and confirm the percentage goes up on the web page within about 5 seconds of the lid closing.
  • Tap Open lid on the phone page and make sure the lid opens.

Troubleshooting

ProblemFix
ESP32 resets when the lid opensThe servo current spike is pulling the 5V rail down. Use a 2A adapter, add the 470 µF capacitor at the servo, and keep the servo ground wire short.
Distance always reads -1 or 0Check the ECHO divider: 1 kΩ from ECHO to the GPIO and 2 kΩ from the GPIO to GND. Make sure the sensor VCC really has 5V.
Lid opens by itselfThe lid sensor sees a wall or the floor. Angle it upward or lower OPEN_CM to 12 to 15 cm.
Fill level jumps aroundSoft rubbish like paper absorbs sound. Keep the sensor in the centre, away from the bin walls, and let the median filter work. Increase the check interval if needed.
Lid does not open fully or buzzesChange ANGLE_OPEN and ANGLE_CLOSED to suit your hinge, or use a metal-gear MG90S or MG996R for a heavy lid.
Web page does not loadThe phone must be on the same 2.4 GHz Wi-Fi. Use the IP address if smartbin.local does not work on your phone.

Ideas to Extend

  • Send a phone notification with ntfy or Telegram when the bin crosses 85 percent.
  • Add a small OLED on the lid to show the fill level without a phone.
  • Run several bins in an office and show them all on one dashboard.

ESP32 Wi-Fi Signal Strength Meter with OLED Display

ESP32 Wi-Fi signal strength meter with SSD1306 OLED display and push button on a breadboard

Build a pocket ESP32 Wi-Fi signal strength meter with an SSD1306 OLED and one button. It lists the strongest networks and shows a live dBm meter with a bar graph. Wiring table, diagram and full code.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUESP32 DevKit
  • Parts5 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 Wi-Fi signal strength meter is a pocket tool that scans the Wi-Fi networks around you and shows the five strongest on a small OLED screen, with their signal level in dBm. Pick one network with a push button and the meter locks on to it, showing a live reading, a quality percentage and a bar graph that updates about four times a second.

It is a small, beginner-friendly build with only three parts: an ESP32 DevKit, a 0.96 inch SSD1306 OLED and a push button. Walk around your home with it to find Wi-Fi dead spots, the best place for a router or repeater, or a good spot for your next ESP8266 or ESP32 IoT device. It never connects to any network, so it needs no Wi-Fi password.

ESP32 Wi-Fi signal strength meter with SSD1306 OLED display and push button on a breadboard

How It Works

  • Scanning: the ESP32 runs in station mode and calls WiFi.scanNetworks(). The results come back sorted from strongest to weakest, and the code keeps the top five, with each network’s name, MAC address (BSSID), channel and RSSI.
  • List screen: the OLED shows the five networks with their RSSI in dBm. The list refreshes every 10 seconds. A short press of the button moves the arrow to the next network.
  • Meter screen: a long press (more than 1 second) locks on to the selected network. The code then scans only that network’s channel, which is much faster than a full scan, and finds the same access point by its MAC address. It shows the RSSI in large digits, a 0 to 100 % quality value and a bar graph. If the network disappears it shows “Lost…”.
  • Reading the numbers: RSSI is negative. Around -50 dBm is excellent, -60 to -67 dBm is good for video calls, -70 dBm is usable for browsing and IoT, and below -80 dBm connections drop often.
  • Status LED: the on-board blue LED on GPIO2 lights during every full scan, and the Serial Monitor prints each meter reading at 115200 baud so you can log it on a laptop.

Components Required

  • ESP32 DevKit V1 (ESP32-WROOM-32, 30 or 38 pin) – 1
  • 0.96 inch SSD1306 I2C OLED display, 128×64 – 1
  • Tactile push button (6×6 mm) – 1
  • Breadboard and male-to-male jumper wires
  • Micro-USB cable, plus a 5V power bank to use it as a portable meter

Wiring Table

Part / pinESP32 pinNotes
OLED VCC3V3Most SSD1306 modules also accept 5V, but 3V3 is safest
OLED GNDGND
OLED SDAGPIO21Default I2C data pin
OLED SCLGPIO22Default I2C clock pin
Push button leg 1GPIO4Internal pull-up, reads LOW when pressed
Push button leg 2GND
Status LEDGPIO2On-board LED, no wiring needed
PowerMicro-USBUSB cable or power bank

Connection Diagram

The illustration above shows the parts and how they fit together. It is a guide for placement only. The pin-accurate drawing below matches the wiring table exactly, so follow it while you build.

ESP32 Wi-Fi Signal Strength Meter – Pin-Accurate Wiring Power USB cable or 5V power bank to the ESP32 DevKit micro-USB socket ESP32 3V3 pin: OLED VCC ESP32 GND: OLED GND and one leg of the push button SSD1306 OLED SDA to GPIO21 SCL to GPIO22 I2C address 0x3C (change OLED_ADDR to 0x3D if needed) Push button One leg to GPIO4, the other leg to GND Internal pull-up enabled in code, no resistor needed Status LED On-board blue LED on GPIO2 lights during each scan
Pin-accurate connection diagram for the ESP32 Wi-Fi signal strength meter.

Code

Install the ESP32 board package in the Arduino IDE (Boards Manager, search “esp32”) and choose ESP32 Dev Module. Install Adafruit SSD1306 and Adafruit GFX from the Library Manager. No Wi-Fi name or password is needed because the meter only scans.

/*
  ESP32 Wi-Fi Signal Strength Meter with OLED Display
  ardiunoprojecthub.online - Project 45

  - Scans nearby Wi-Fi networks and lists the 5 strongest on a 0.96" SSD1306 OLED.
  - Short press of the button: move the cursor to the next network.
  - Long press (over 1 s): lock on to the selected network and show a live
    RSSI meter (dBm, % quality and a bar graph). Long press again to go back.
  - The meter mode is handy for finding the best place for a router, repeater
    or an IoT device.

  Wiring:
    OLED VCC -> 3V3, GND -> GND, SDA -> GPIO21, SCL -> GPIO22
    Push button -> GPIO4 and GND (internal pull-up)
    Status LED (+) -> GPIO2 (on-board LED on most DevKits)

  Libraries: Adafruit SSD1306 and Adafruit GFX (Library Manager).
  No Wi-Fi password is needed: the ESP32 only scans, it never connects.
*/
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_W 128
#define SCREEN_H 64
#define OLED_ADDR 0x3C        // change to 0x3D if your OLED uses that address
#define BUTTON_PIN 4
#define LED_PIN 2
#define MAX_LIST 5

Adafruit_SSD1306 oled(SCREEN_W, SCREEN_H, &Wire, -1);

String ssids[MAX_LIST];       // names of the strongest networks
uint8_t bssids[MAX_LIST][6];  // MAC address of each access point
int channels[MAX_LIST];
int rssis[MAX_LIST];
int listCount = 0;
int cursorPos = 0;
bool meterMode = false;
unsigned long lastScan = 0;

// Convert dBm to a rough 0-100 % quality value
int rssiToPercent(int rssi) {
  if (rssi <= -100) return 0;
  if (rssi >= -50) return 100;
  return 2 * (rssi + 100);
}

// Scan and keep the strongest MAX_LIST networks (results come sorted by RSSI)
void scanNetworks() {
  digitalWrite(LED_PIN, HIGH);
  int n = WiFi.scanNetworks(false, true);   // blocking scan, include hidden
  listCount = 0;
  for (int i = 0; i < n && listCount < MAX_LIST; i++) {
    String name = WiFi.SSID(i);
    if (name.length() == 0) name = "(hidden)";
    ssids[listCount] = name;
    memcpy(bssids[listCount], WiFi.BSSID(i), 6);
    channels[listCount] = WiFi.channel(i);
    rssis[listCount] = WiFi.RSSI(i);
    listCount++;
  }
  WiFi.scanDelete();
  if (cursorPos >= listCount) cursorPos = 0;
  digitalWrite(LED_PIN, LOW);
}

// Re-scan only the locked network's channel and return its RSSI (or 0 if lost)
int readLockedRssi() {
  int n = WiFi.scanNetworks(false, true, false, 120, channels[cursorPos]);
  int found = 0;
  for (int i = 0; i < n; i++) {
    if (memcmp(WiFi.BSSID(i), bssids[cursorPos], 6) == 0) {
      found = WiFi.RSSI(i);
      break;
    }
  }
  WiFi.scanDelete();
  return found;
}

void drawList() {
  oled.clearDisplay();
  oled.setTextSize(1);
  oled.setCursor(0, 0);
  oled.print("Wi-Fi scan  ");
  oled.print(listCount);
  oled.println(" found");
  oled.drawLine(0, 9, 127, 9, SSD1306_WHITE);
  if (listCount == 0) {
    oled.setCursor(0, 24);
    oled.println("No networks found");
  }
  for (int i = 0; i < listCount; i++) {
    int y = 12 + i * 10;
    oled.setCursor(0, y);
    oled.print(i == cursorPos ? ">" : " ");
    oled.print(ssids[i].substring(0, 13));   // keep it on one line
    oled.setCursor(98, y);
    oled.print(rssis[i]);
  }
  oled.display();
}

void drawMeter(int rssi) {
  oled.clearDisplay();
  oled.setTextSize(1);
  oled.setCursor(0, 0);
  oled.print(ssids[cursorPos].substring(0, 15));
  oled.setCursor(104, 0);
  oled.print("C");
  oled.print(channels[cursorPos]);
  if (rssi == 0) {
    oled.setTextSize(2);
    oled.setCursor(10, 28);
    oled.print("Lost...");
  } else {
    int pct = rssiToPercent(rssi);
    oled.setTextSize(2);
    oled.setCursor(0, 16);
    oled.print(rssi);
    oled.print(" dBm");
    oled.setTextSize(1);
    oled.setCursor(0, 36);
    oled.print("Quality: ");
    oled.print(pct);
    oled.print("%");
    oled.drawRect(0, 48, 128, 14, SSD1306_WHITE);           // bar outline
    oled.fillRect(2, 50, map(pct, 0, 100, 0, 124), 10, SSD1306_WHITE);
  }
  oled.display();
}

// Returns 0 = no press, 1 = short press, 2 = long press
int readButton() {
  if (digitalRead(BUTTON_PIN) == HIGH) return 0;
  delay(30);                                   // debounce
  if (digitalRead(BUTTON_PIN) == HIGH) return 0;
  unsigned long start = millis();
  while (digitalRead(BUTTON_PIN) == LOW) delay(5);
  return (millis() - start > 1000) ? 2 : 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  Wire.begin(21, 22);
  if (!oled.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println("OLED not found - check wiring and address");
    while (true) delay(1000);
  }
  oled.setTextColor(SSD1306_WHITE);
  oled.clearDisplay();
  oled.setCursor(0, 24);
  oled.print("Scanning Wi-Fi...");
  oled.display();
  WiFi.mode(WIFI_STA);   // station mode, but we never connect
  WiFi.disconnect();
  delay(100);
  scanNetworks();
  drawList();
  lastScan = millis();
}

void loop() {
  int press = readButton();
  if (press == 1 && !meterMode && listCount > 0) {
    cursorPos = (cursorPos + 1) % listCount;
    drawList();
  } else if (press == 2 && listCount > 0) {
    meterMode = !meterMode;
    if (!meterMode) { scanNetworks(); drawList(); lastScan = millis(); }
  }

  if (meterMode) {
    int rssi = readLockedRssi();             // about 4 updates per second
    drawMeter(rssi);
    Serial.printf("%s  %d dBm\n", ssids[cursorPos].c_str(), rssi);
  } else if (millis() - lastScan > 10000) {  // refresh the list every 10 s
    scanNetworks();
    drawList();
    lastScan = millis();
  }
}

Testing and Using the Meter

  • Upload the sketch. The OLED shows “Scanning Wi-Fi…” and then the list of the strongest networks.
  • Short-press the button to move the arrow to your own network, then hold it for more than one second to open the meter screen.
  • Stand next to the router and note the reading (usually -30 to -45 dBm). Then walk to each room and note the value.
  • Rooms below -75 dBm are weak spots. Move the router higher, away from walls and metal, or add a repeater halfway, and measure again.
  • Hold the button for one second again to return to the list.

Troubleshooting

ProblemFix
OLED stays blankCheck SDA on GPIO21 and SCL on GPIO22. Run an I2C scanner sketch; if the address is 0x3D, change OLED_ADDR.
“No networks found”Make sure you are within range of a 2.4 GHz network. The ESP32 cannot see 5 GHz Wi-Fi.
Your network is not in the listOnly the five strongest are shown. Move closer to the router, or change MAX_LIST to a bigger number and reduce the text size.
Button does nothingUse two legs on opposite sides of the tactile switch, or turn it 90 degrees on the breadboard.
Reading jumps around a lotThat is normal for Wi-Fi. Hold the meter still for a few seconds and use the average value.

Ideas to Extend

  • Add a small LiPo battery and a TP4056 charger board to make it fully portable.
  • Show a channel graph so you can pick the least crowded 2.4 GHz channel for your router.
  • Add a buzzer that beeps faster as the signal gets stronger, like a metal detector, to find hidden access points.

ESP32 Air Quality Monitor with PMS5003, BME280, MQ-135, OLED & Web Dashboard

ESP32 air quality monitor with PMS5003, BME280, MQ-135, SSD1306 OLED, RGB LED and buzzer

Build an ESP32 air quality monitor with a PMS5003 dust sensor, BME280, MQ-135, OLED, RGB AQI LED, buzzer and a live Wi-Fi dashboard. Wiring table, diagram and full code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUESP32 DevKit
  • Parts11 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 air quality monitor measures the fine dust you breathe (PM1.0, PM2.5 and PM10) with a Plantower PMS5003 laser sensor, adds temperature, humidity and pressure from a BME280, and a general gas level from an MQ-135. It works out an AQI value for PM2.5 using the Indian National AQI bands, shows everything on a 0.96 inch OLED, lights an RGB LED from green to red, beeps when the air turns poor, and serves a live dashboard you can open on any phone on your Wi-Fi.

It is a big, multi-sensor IoT build that combines UART, I2C, ADC and PWM on one board. It is useful for bedrooms, classrooms, workshops, and for checking how well an air purifier works during winter smog.

ESP32 air quality monitor with PMS5003, BME280, MQ-135, SSD1306 OLED, RGB LED and buzzer

How It Works

  • PMS5003 dust sensor: a small fan pulls air through a laser beam. Light scattered by particles is counted and the sensor sends a 32-byte frame every second over serial at 9600 baud. The ESP32 reads it on UART2 (GPIO16/17), checks the checksum and takes the atmospheric PM1.0, PM2.5 and PM10 values in µg/m³.
  • AQI calculation: the PM2.5 value is converted with the Indian NAQI breakpoints (0-30 Good, 31-60 Satisfactory, 61-90 Moderate, 91-120 Poor, 121-250 Very Poor, above 250 Severe). The official AQI uses 24-hour averages, so the live number is a guide, not a certified reading.
  • BME280: reports temperature, relative humidity and air pressure over I2C on the same bus as the OLED (GPIO21 SDA, GPIO22 SCL).
  • MQ-135: its heater runs on 5V and the analog output rises when gases such as smoke, alcohol or ammonia are present. A 10k/20k divider keeps the signal below 3.3V for GPIO34. The value is shown as a raw relative level, because the MQ-135 is not accurate enough for real ppm readings without calibration.
  • Status outputs: the RGB LED shows the AQI colour (purple means no data from the PMS5003 for 10 seconds). Above AQI 200 the buzzer gives a short beep once a minute through a BC547 transistor.
  • Web dashboard: the ESP32 joins your Wi-Fi and serves a page at its IP address. The page fetches /data as JSON every 3 seconds, so the cards update without reloading.

Components Required

  • ESP32 DevKit V1 (30-pin) – 1
  • Plantower PMS5003 particulate sensor with its 8-pin cable (or an adapter board) – 1
  • BME280 temperature, humidity and pressure module (I2C) – 1
  • MQ-135 air quality sensor module – 1
  • 0.96 inch SSD1306 I2C OLED, 128×64 – 1
  • Common-cathode RGB LED (5 mm) – 1
  • Active 5V buzzer – 1
  • BC547 NPN transistor – 1
  • Resistors: 220 Ω – 3, 1k – 1, 10k – 1, 20k – 1
  • 5V 2A USB adapter and cable – 1
  • Breadboard or perfboard and jumper wires

Wiring Table

Module pinESP32 pinNotes
PMS5003 pin 1 (VCC)VIN (5V)The fan needs 5V; logic is 3.3V so it connects directly
PMS5003 pin 2 (GND)GND
PMS5003 pin 3 (SET)GPIO4HIGH keeps the sensor running
PMS5003 pin 4 (RX)GPIO17 (TX2)
PMS5003 pin 5 (TX)GPIO16 (RX2)
PMS5003 pins 6, 7, 8Not connectedRESET has an internal pull-up
BME280 VIN / GND3V3 / GND
BME280 SDA / SCLGPIO21 / GPIO22I2C address 0x76 (0x77 also tried)
OLED VCC / GND3V3 / GND
OLED SDA / SCLGPIO21 / GPIO22Shared I2C bus, address 0x3C
MQ-135 VCC / GNDVIN (5V) / GNDLet it warm up for 24 hours the first time
MQ-135 AOGPIO34 via 10k20k from GPIO34 to GND (divider)
RGB LED red / green / blueGPIO25 / GPIO26 / GPIO27220 Ω on each leg
RGB LED cathodeGNDLongest leg
BC547 baseGPIO33 via 1kEmitter to GND
Buzzer +5VBuzzer – to BC547 collector

Connection Diagram

The illustration above shows the general layout; its wire routes are only for orientation. The pin-accurate drawing below matches the wiring table exactly, so follow it while building.

ESP32 Air Quality Monitor – Pin-Accurate Wiring Power USB 5V: ESP32 VIN feeds PMS5003 pin 1 (VCC 5V) and MQ-135 VCC ESP32 GND: common ground for every module PMS5003 Pin 2 GND to GND, pin 3 SET to GPIO4 Pin 4 RX to GPIO17 (TX2), pin 5 TX to GPIO16 (RX2) Pins 6 RESET and 7, 8 NC: leave unconnected BME280 VIN to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x76) SSD1306 OLED VCC to 3V3, GND to GND SDA to GPIO21, SCL to GPIO22 (address 0x3C) MQ-135 VCC to 5V (VIN), GND to GND AO through 10k to GPIO34, 20k from GPIO34 to GND RGB LED Red to GPIO25, green to GPIO26, blue to GPIO27, each via 220 Ω Common cathode (longest leg) to GND Buzzer GPIO33 via 1k to BC547 base, emitter to GND Buzzer + to 5V, buzzer – to BC547 collector
Pin-accurate connection diagram for the ESP32 air quality monitor.

Code

Install the ESP32 board package in the Arduino IDE and choose ESP32 Dev Module. From the Library Manager install Adafruit BME280, Adafruit Unified Sensor, Adafruit SSD1306 and Adafruit GFX. The PMS5003 is read directly, so it needs no library. Replace the Wi-Fi placeholders with your own network name and password, upload, and open the Serial Monitor at 115200 baud to see the dashboard address.

/*
  ESP32 Air Quality Monitor
  PMS5003 (PM1.0 / PM2.5 / PM10) + BME280 (temperature, humidity, pressure)
  + MQ-135 (relative gas level) + SSD1306 OLED + RGB status LED + buzzer
  + Wi-Fi web dashboard with live JSON data.

  Board: ESP32 Dev Module (ESP32 DevKit V1)
  Libraries: Adafruit BME280, Adafruit Unified Sensor, Adafruit SSD1306, Adafruit GFX
  The PMS5003 is read directly over UART2 (no extra library needed).
*/

#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_BME280.h>

// ---------- User settings ----------
const char* WIFI_SSID     = "YOUR_WIFI_SSID";      // placeholder: put your Wi-Fi name
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";  // placeholder: put your Wi-Fi password

// ---------- Pins ----------
#define PMS_RX_PIN   16   // ESP32 RX2  <- PMS5003 TX (pin 5)
#define PMS_TX_PIN   17   // ESP32 TX2  -> PMS5003 RX (pin 4)
#define PMS_SET_PIN  4    // HIGH = sensor running, LOW = sleep (fan off)
#define MQ135_PIN    34   // MQ-135 AO through a 10k/20k divider (ADC1, input only)
#define LED_R_PIN    25   // RGB LED red   (through 220 ohm)
#define LED_G_PIN    26   // RGB LED green (through 220 ohm)
#define LED_B_PIN    27   // RGB LED blue  (through 220 ohm)
#define BUZZER_PIN   33   // Active buzzer via BC547 transistor
// I2C: SDA = GPIO21, SCL = GPIO22 (BME280 at 0x76, OLED at 0x3C)

// ---------- Objects ----------
Adafruit_SSD1306 display(128, 64, &Wire, -1);
Adafruit_BME280 bme;
WebServer server(80);
HardwareSerial pmsSerial(2);

// ---------- Readings ----------
struct Readings {
  uint16_t pm1 = 0, pm25 = 0, pm10 = 0;
  float tempC = NAN, hum = NAN, pressHpa = NAN;
  int gasRaw = 0;          // 0-4095 relative gas level from MQ-135
  int aqi = 0;             // India NAQI sub-index for PM2.5
  bool pmsOk = false;
} r;

bool bmeOk = false;
unsigned long lastPmsFrame = 0;
unsigned long lastScreen = 0;
unsigned long lastBeep = 0;

// ---------- India NAQI sub-index for PM2.5 (24-h breakpoints, used here as live guide) ----------
int pm25ToAqi(float c) {
  // {C_low, C_high, I_low, I_high}
  const float bp[6][4] = {
    {0, 30, 0, 50}, {31, 60, 51, 100}, {61, 90, 101, 200},
    {91, 120, 201, 300}, {121, 250, 301, 400}, {251, 500, 401, 500}
  };
  if (c > 500) return 500;
  for (int i = 0; i < 6; i++) {
    if (c <= bp[i][1]) {
      if (c < bp[i][0]) c = bp[i][0];
      return (int)((bp[i][3] - bp[i][2]) / (bp[i][1] - bp[i][0]) * (c - bp[i][0]) + bp[i][2]);
    }
  }
  return 500;
}

const char* aqiLabel(int aqi) {
  if (aqi <= 50)  return "Good";
  if (aqi <= 100) return "Satisfactory";
  if (aqi <= 200) return "Moderate";
  if (aqi <= 300) return "Poor";
  if (aqi <= 400) return "Very Poor";
  return "Severe";
}

// ---------- RGB LED colour by AQI ----------
void setLed(uint8_t red, uint8_t green, uint8_t blue) {
  analogWrite(LED_R_PIN, red);
  analogWrite(LED_G_PIN, green);
  analogWrite(LED_B_PIN, blue);
}

void showAqiColour(int aqi) {
  if (aqi <= 50)       setLed(0, 255, 0);     // green
  else if (aqi <= 100) setLed(120, 255, 0);   // light green
  else if (aqi <= 200) setLed(255, 180, 0);   // yellow
  else if (aqi <= 300) setLed(255, 80, 0);    // orange
  else                 setLed(255, 0, 0);     // red
}

// ---------- PMS5003 frame reader ----------
// Frame: 0x42 0x4D, length(2), 13 data words, checksum(2) = 32 bytes total
bool readPms() {
  static uint8_t buf[32];
  static uint8_t idx = 0;
  bool gotFrame = false;

  while (pmsSerial.available()) {
    uint8_t b = pmsSerial.read();
    if (idx == 0 && b != 0x42) continue;          // wait for start byte 1
    if (idx == 1 && b != 0x4D) { idx = 0; continue; } // start byte 2
    buf[idx++] = b;
    if (idx == 32) {
      idx = 0;
      uint16_t sum = 0;
      for (int i = 0; i < 30; i++) sum += buf[i];
      uint16_t check = (buf[30] << 8) | buf[31];
      if (sum == check) {
        // Atmospheric-environment values (words 4-6) are the ones to show
        r.pm1  = (buf[10] << 8) | buf[11];
        r.pm25 = (buf[12] << 8) | buf[13];
        r.pm10 = (buf[14] << 8) | buf[15];
        r.pmsOk = true;
        gotFrame = true;
      }
    }
  }
  return gotFrame;
}

// ---------- Other sensors ----------
void readOtherSensors() {
  if (bmeOk) {
    r.tempC = bme.readTemperature();
    r.hum = bme.readHumidity();
    r.pressHpa = bme.readPressure() / 100.0F;
  }
  // Average 16 samples to smooth the MQ-135 output
  long total = 0;
  for (int i = 0; i < 16; i++) total += analogRead(MQ135_PIN);
  r.gasRaw = total / 16;
}

// ---------- OLED ----------
void drawScreen() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("AQI ");
  display.print(r.aqi);
  display.print(" ");
  display.print(aqiLabel(r.aqi));

  display.setTextSize(2);
  display.setCursor(0, 12);
  display.print("PM2.5 ");
  display.print(r.pm25);

  display.setTextSize(1);
  display.setCursor(0, 32);
  display.printf("PM1 %u  PM10 %u", r.pm1, r.pm10);
  display.setCursor(0, 42);
  if (bmeOk) display.printf("%.1fC  %.0f%%  %.0fhPa", r.tempC, r.hum, r.pressHpa);
  else display.print("BME280 not found");
  display.setCursor(0, 54);
  display.printf("Gas %d  ", r.gasRaw);
  if (WiFi.status() == WL_CONNECTED) display.print(WiFi.localIP());
  else display.print("No Wi-Fi");
  display.display();
}

// ---------- Web dashboard ----------
const char PAGE[] PROGMEM = R"HTML(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32 Air Quality</title>
<style>
body{font-family:Arial,sans-serif;background:#f4f6f8;margin:0;padding:16px;text-align:center}
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;max-width:700px;margin:auto}
.card{background:#fff;border-radius:10px;padding:14px;box-shadow:0 1px 4px #0002}
.v{font-size:28px;font-weight:bold}.l{color:#666;font-size:13px}
#aqi{font-size:48px;font-weight:bold}
</style></head><body>
<h2>ESP32 Air Quality Monitor</h2>
<div class="card" style="max-width:700px;margin:0 auto 12px"><div id="aqi">--</div><div id="lab" class="l">loading</div></div>
<div class="grid">
<div class="card"><div class="v" id="pm25">--</div><div class="l">PM2.5 (ug/m3)</div></div>
<div class="card"><div class="v" id="pm10">--</div><div class="l">PM10 (ug/m3)</div></div>
<div class="card"><div class="v" id="pm1">--</div><div class="l">PM1.0 (ug/m3)</div></div>
<div class="card"><div class="v" id="t">--</div><div class="l">Temperature (C)</div></div>
<div class="card"><div class="v" id="h">--</div><div class="l">Humidity (%)</div></div>
<div class="card"><div class="v" id="p">--</div><div class="l">Pressure (hPa)</div></div>
<div class="card"><div class="v" id="g">--</div><div class="l">Gas level (MQ-135 raw)</div></div>
</div>
<script>
const col=a=>a<=50?'#2e7d32':a<=100?'#7cb342':a<=200?'#f9a825':a<=300?'#ef6c00':'#c62828';
async function up(){try{const d=await (await fetch('/data')).json();
for(const k of ['pm25','pm10','pm1','g'])document.getElementById(k).textContent=d[k];
document.getElementById('t').textContent=d.t;document.getElementById('h').textContent=d.h;
document.getElementById('p').textContent=d.p;
const a=document.getElementById('aqi');a.textContent=d.aqi;a.style.color=col(d.aqi);
document.getElementById('lab').textContent='AQI (PM2.5): '+d.label;}catch(e){}}
up();setInterval(up,3000);
</script></body></html>
)HTML";

void handleRoot() { server.send_P(200, "text/html", PAGE); }

void handleData() {
  char json[256];
  snprintf(json, sizeof(json),
    "{\"pm1\":%u,\"pm25\":%u,\"pm10\":%u,\"t\":\"%.1f\",\"h\":\"%.0f\",\"p\":\"%.0f\",\"g\":%d,\"aqi\":%d,\"label\":\"%s\"}",
    r.pm1, r.pm25, r.pm10, r.tempC, r.hum, r.pressHpa, r.gasRaw, r.aqi, aqiLabel(r.aqi));
  server.send(200, "application/json", json);
}

// ---------- Setup ----------
void setup() {
  Serial.begin(115200);

  pinMode(PMS_SET_PIN, OUTPUT);
  digitalWrite(PMS_SET_PIN, HIGH);        // keep the PMS5003 awake
  pinMode(BUZZER_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  pinMode(LED_R_PIN, OUTPUT);
  pinMode(LED_G_PIN, OUTPUT);
  pinMode(LED_B_PIN, OUTPUT);
  setLed(0, 0, 255);                      // blue while starting
  analogReadResolution(12);

  pmsSerial.begin(9600, SERIAL_8N1, PMS_RX_PIN, PMS_TX_PIN);
  Wire.begin(21, 22);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("Air Quality Monitor");
  display.println("Warming up sensors...");
  display.display();

  bmeOk = bme.begin(0x76) || bme.begin(0x77);
  if (!bmeOk) Serial.println("BME280 not found, check wiring");

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) delay(250);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Dashboard: http://");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("Wi-Fi not connected, running offline");
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.begin();
}

// ---------- Loop ----------
void loop() {
  server.handleClient();

  if (readPms()) {
    lastPmsFrame = millis();
    r.aqi = pm25ToAqi(r.pm25);
    showAqiColour(r.aqi);
  }
  // No valid frame for 10 s: show purple to flag a PMS5003 problem
  if (millis() - lastPmsFrame > 10000) {
    r.pmsOk = false;
    setLed(150, 0, 255);
  }

  if (millis() - lastScreen > 2000) {
    lastScreen = millis();
    readOtherSensors();
    drawScreen();
  }

  // Short beep every 60 s while AQI is Poor (above 200)
  if (r.pmsOk && r.aqi > 200 && millis() - lastBeep > 60000) {
    lastBeep = millis();
    digitalWrite(BUZZER_PIN, HIGH);
    delay(300);
    digitalWrite(BUZZER_PIN, LOW);
  }
}

Troubleshooting

ProblemFix
LED stays purple and PM values are 0TX and RX are probably swapped. PMS5003 TX (pin 5) must go to GPIO16. Also check that SET is HIGH and the fan is spinning.
BME280 not foundCheck SDA/SCL and the address. Some purple boards are BMP280 (no humidity), which this code does not support.
OLED is blankCheck the address 0x3C and that VCC is on 3V3. Run an I2C scanner if unsure.
MQ-135 value keeps fallingNormal for a new sensor. Leave it powered for a day to burn in, then note the clean-air value as your baseline.
PM readings jump in humid weatherAbove about 85% humidity water droplets are counted as dust. Compare with the BME280 humidity before trusting a high reading.

Ideas to Extend

  • Log readings to Google Sheets or ThingSpeak every 5 minutes for daily graphs.
  • Put the PMS5003 to sleep (SET LOW) between readings to extend the fan life.
  • Switch an air purifier through a relay when AQI goes above 150.
  • Add an SCD40 sensor for true CO2 readings in closed rooms.

ESP32 Energy Meter with PZEM-004T, OLED & Web Dashboard

ESP32 energy meter wiring illustration with PZEM-004T module, CT coil on the live wire, OLED display, push button and phone dashboard

Build an ESP32 energy meter with a PZEM-004T v3.0 module that shows voltage, current, power, kWh and bill on an OLED and a Wi-Fi web dashboard. Wiring, diagram and full code.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUESP32 DevKit
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 energy meter measures how much electricity an appliance or a whole room uses. A PZEM-004T v3.0 module reads the mains voltage, current, power, energy in kWh, frequency and power factor, and the ESP32 shows them on a small OLED screen and on a live web dashboard that opens on any phone connected to your Wi-Fi.

It also estimates your electricity bill from the units used, so you can see what your fridge, geyser or AC really costs to run. A JSON endpoint lets you log the data in Home Assistant, Node-RED or a spreadsheet.

ESP32 energy meter wiring illustration with PZEM-004T module, CT coil on the live wire, OLED display, push button and phone dashboard

How It Works

  • Measurement: the PZEM-004T senses voltage directly from its L and N terminals and current through its CT (current transformer) coil clamped around the live wire. Its own chip calculates power, energy, frequency and power factor and keeps the kWh count even when the ESP32 restarts.
  • Communication: the module talks Modbus RTU over a TTL serial port at 9600 baud. The ESP32 uses its second hardware serial port (UART2 on GPIO16 and GPIO17) so the USB serial monitor stays free for debugging.
  • Display: once per second the ESP32 reads all six values and draws them on the 0.96 inch SSD1306 OLED, with the power in large digits and a HIGH LOAD warning above 2000 W.
  • Web dashboard: the ESP32 runs a small web server. Open its IP address in a browser to see six live tiles that refresh every 3 seconds, the estimated bill, and a button to reset the kWh counter. /json returns the same data for other software.
  • Reset button: holding the push button on GPIO4 for 3 seconds clears the energy counter stored in the PZEM module, for example at the start of each billing month.

Components Required

  • ESP32 development board (ESP32 Dev Module / DevKit V1) – 1
  • PZEM-004T v3.0 module with 100 A split or closed CT coil – 1
  • 0.96 inch SSD1306 I2C OLED (128×64) – 1
  • Push button – 1
  • 5 V USB power adapter and micro-USB cable
  • Jumper wires, plastic enclosure, screw terminals
  • Mains cable with plug and socket for the load you want to measure

Wiring Table

FromToNotes
PZEM 5VESP32 VIN (5V)Powers the PZEM TTL interface
PZEM GNDESP32 GND
PZEM TXESP32 GPIO16 (RX2)Serial data from meter
PZEM RXESP32 GPIO17 (TX2)Serial data to meter
OLED VCCESP32 3V3
OLED GNDESP32 GND
OLED SDAESP32 GPIO21
OLED SCLESP32 GPIO22I2C address 0x3C
Push button leg 1ESP32 GPIO4Internal pull-up, hold 3 s to reset kWh
Push button leg 2ESP32 GND
PZEM L / N terminalsMains Live / Neutral230 V AC, power OFF while wiring
CT coilAround the LIVE wire to the loadOnly one wire passes through the coil

Connection Diagram

The illustration above shows the general layout. The pin-accurate drawing below matches the wiring table exactly, so follow it when you build the circuit.

ESP32 Energy Meter with PZEM-004T – Pin-Accurate Wiring ESP32 Dev Module VIN (5V): PZEM 5V and USB supply 3V3: OLED VCC GND: PZEM GND, OLED GND, button GPIO16 (RX2): PZEM TX GPIO17 (TX2): PZEM RX GPIO21 (SDA): OLED SDA GPIO22 (SCL): OLED SCL GPIO4: reset push button PZEM-004T v3.0 (TTL side) 5V: ESP32 VIN (5V) GND: ESP32 GND TX: ESP32 GPIO16 RX: ESP32 GPIO17 PZEM-004T (mains side) L and N terminals: mains Live and Neutral (voltage sense) CT coil: clamp around the LIVE wire only, going to the load SSD1306 OLED 0.96in VCC: 3V3 GND: GND SDA: GPIO21 SCL: GPIO22 Push Button Leg 1: GPIO4 (internal pull-up) Leg 2: GND Warning: the PZEM mains terminals carry 230 V AC. Wire them with the power OFF and keep them inside a closed box.
Pin-accurate connection diagram for the ESP32 PZEM-004T energy meter.

Safety First

  • The L and N terminals of the PZEM-004T are connected to 230 V mains. Make all connections with the main switch OFF and the plug removed.
  • Put the PZEM module and its mains terminals inside a closed plastic box. Never touch the board while it is powered from mains.
  • Pass only the live wire through the CT coil. If both live and neutral pass through it, the current cancels out and reads zero.
  • If you are not comfortable with mains wiring, ask a qualified electrician to do the mains side.

Code

In the Arduino IDE install the ESP32 board package and these libraries from the Library Manager: PZEM004Tv30 (by Jakub Mandula), Adafruit SSD1306 and Adafruit GFX. Choose ESP32 Dev Module as the board, replace the Wi-Fi placeholders, set your tariff in COST_PER_KWH, and upload.

/*
  ESP32 Energy Meter with PZEM-004T v3.0, OLED and Web Dashboard
  ---------------------------------------------------------------
  - Reads voltage, current, power, energy (kWh), frequency and power factor
    from a PZEM-004T v3.0 module over Modbus (UART2: GPIO16 RX, GPIO17 TX).
  - Shows live values on a 0.96" SSD1306 I2C OLED (SDA GPIO21, SCL GPIO22).
  - Serves a web dashboard on your Wi-Fi with auto-refresh and a JSON API.
  - Push button on GPIO4 (hold 3 s) or the web button resets the kWh counter.
  - Estimates the bill using your price per unit (edit COST_PER_KWH).

  Libraries: PZEM004Tv30 (by Jakub Mandula), Adafruit SSD1306, Adafruit GFX.
  Board: ESP32 Dev Module.
*/
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <PZEM004Tv30.h>

// ---------- User settings ----------
const char* WIFI_SSID     = "YOUR_WIFI_SSID";      // placeholder
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";  // placeholder
const float COST_PER_KWH  = 7.0;    // your electricity tariff per unit (kWh)
const float POWER_ALERT_W = 2000.0; // OLED shows "HIGH LOAD" above this

// ---------- Pins ----------
#define PZEM_RX_PIN 16   // ESP32 RX2  <- PZEM TX
#define PZEM_TX_PIN 17   // ESP32 TX2  -> PZEM RX
#define RESET_BTN   4    // push button to GND (internal pull-up)

PZEM004Tv30 pzem(Serial2, PZEM_RX_PIN, PZEM_TX_PIN);
Adafruit_SSD1306 display(128, 64, &Wire, -1);
WebServer server(80);

// Latest readings (NAN means "no reading")
float voltage = NAN, current = NAN, power = NAN, energy = NAN, freq = NAN, pf = NAN;
unsigned long lastRead = 0;
unsigned long btnPressedAt = 0;

// Read every value from the PZEM module
void readPzem() {
  voltage = pzem.voltage();
  current = pzem.current();
  power   = pzem.power();
  energy  = pzem.energy();
  freq    = pzem.frequency();
  pf      = pzem.pf();
  if (isnan(voltage)) {
    Serial.println("PZEM not responding - check wiring and mains connection");
  } else {
    Serial.printf("V=%.1f I=%.3f P=%.1f E=%.3f F=%.1f PF=%.2f\n",
                  voltage, current, power, energy, freq, pf);
  }
}

// Draw the readings on the OLED
void drawOled() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  if (isnan(voltage)) {
    display.println("PZEM-004T");
    display.println("No reading.");
    display.println("Check wiring/mains.");
  } else {
    display.setTextSize(2);
    display.printf("%.0fW\n", power);          // big power value
    display.setTextSize(1);
    display.printf("%.1fV  %.2fA\n", voltage, current);
    display.printf("%.3f kWh\n", energy);
    display.printf("PF %.2f  %.1fHz\n", pf, freq);
    display.printf("Bill: Rs %.2f\n", energy * COST_PER_KWH);
    if (power > POWER_ALERT_W) display.print("!! HIGH LOAD !!");
  }
  // Small Wi-Fi indicator in the top right corner
  display.setTextSize(1);
  display.setCursor(104, 0);
  display.print(WiFi.status() == WL_CONNECTED ? "WiFi" : "----");
  display.display();
}

// Helper: number to text, "--" when the value is missing
String num(float v, int digits) {
  return isnan(v) ? String("--") : String(v, digits);
}

// Web dashboard page (refreshes itself every 3 seconds)
void handleRoot() {
  String html = F("<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>"
                  "<meta http-equiv='refresh' content='3'><title>ESP32 Energy Meter</title>"
                  "<style>body{font-family:Arial;background:#f4f6f8;text-align:center}"
                  ".g{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;max-width:420px;margin:auto}"
                  ".c{background:#fff;border-radius:10px;padding:14px;box-shadow:0 1px 4px #0002}"
                  ".v{font-size:26px;font-weight:bold;color:#1565c0}button{margin-top:16px;padding:10px 18px}</style>"
                  "</head><body><h2>ESP32 Energy Meter</h2><div class='g'>");
  html += "<div class='c'>Voltage<div class='v'>" + num(voltage, 1) + " V</div></div>";
  html += "<div class='c'>Current<div class='v'>" + num(current, 3) + " A</div></div>";
  html += "<div class='c'>Power<div class='v'>" + num(power, 1) + " W</div></div>";
  html += "<div class='c'>Energy<div class='v'>" + num(energy, 3) + " kWh</div></div>";
  html += "<div class='c'>Frequency<div class='v'>" + num(freq, 1) + " Hz</div></div>";
  html += "<div class='c'>Power factor<div class='v'>" + num(pf, 2) + "</div></div>";
  html += "</div><p>Estimated bill: <b>Rs " + num(isnan(energy) ? NAN : energy * COST_PER_KWH, 2) + "</b></p>";
  html += F("<form action='/reset' method='POST' onsubmit=\"return confirm('Reset kWh counter?')\">"
            "<button>Reset energy counter</button></form></body></html>");
  server.send(200, "text/html", html);
}

// JSON API for Home Assistant, Node-RED or a spreadsheet logger
void handleJson() {
  String j = "{\"voltage\":" + num(voltage, 1) + ",\"current\":" + num(current, 3) +
             ",\"power\":" + num(power, 1) + ",\"energy\":" + num(energy, 3) +
             ",\"frequency\":" + num(freq, 1) + ",\"pf\":" + num(pf, 2) + "}";
  j.replace("--", "null");
  server.send(200, "application/json", j);
}

// Reset the kWh counter stored inside the PZEM module
void handleReset() {
  bool ok = pzem.resetEnergy();
  Serial.println(ok ? "Energy counter reset" : "Energy reset failed");
  server.sendHeader("Location", "/");
  server.send(303);
}

void connectWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 15000) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Dashboard: http://");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("Wi-Fi not connected, OLED still works. Will retry.");
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(RESET_BTN, INPUT_PULLUP);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("OLED not found at 0x3C");
  }
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("ESP32 Energy Meter");
  display.println("Connecting Wi-Fi...");
  display.display();

  connectWiFi();
  if (WiFi.status() == WL_CONNECTED) {
    display.println(WiFi.localIP());
    display.display();
    delay(2000);
  }

  server.on("/", handleRoot);
  server.on("/json", handleJson);
  server.on("/reset", HTTP_POST, handleReset);
  server.begin();
}

void loop() {
  server.handleClient();

  // Read the meter and refresh the OLED once per second
  if (millis() - lastRead >= 1000) {
    lastRead = millis();
    readPzem();
    drawOled();
  }

  // Hold the button for 3 seconds to reset the kWh counter
  if (digitalRead(RESET_BTN) == LOW) {
    if (btnPressedAt == 0) btnPressedAt = millis();
    if (millis() - btnPressedAt > 3000) {
      pzem.resetEnergy();
      Serial.println("Energy counter reset by button");
      btnPressedAt = 0;
      while (digitalRead(RESET_BTN) == LOW) delay(10);  // wait for release
    }
  } else {
    btnPressedAt = 0;
  }

  // Reconnect Wi-Fi every 30 s if the router dropped
  static unsigned long lastWifiTry = 0;
  if (WiFi.status() != WL_CONNECTED && millis() - lastWifiTry > 30000) {
    lastWifiTry = millis();
    WiFi.disconnect();
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  }
}

Testing

  • Open the Serial Monitor at 115200 baud. It prints the dashboard address, for example http://192.168.1.50.
  • With mains connected and no load, voltage should read about 220 to 240 V and current close to 0 A.
  • Plug in a known load, such as a 100 W bulb or a 1000 W kettle, and check that the power reading is close to its rating.
  • Open the dashboard on your phone and watch the tiles refresh every 3 seconds.

Troubleshooting

ProblemFix
OLED says No readingThe PZEM needs mains on its L and N terminals to answer. Also check that TX goes to GPIO16 and RX to GPIO17 (crossed).
Current reads 0 A with a load onMake sure only the live wire passes through the CT coil and the coil plug is fully inserted.
Dashboard does not openCheck the IP in the Serial Monitor and that your phone is on the same Wi-Fi network.
Readings freeze sometimesUse a good 5 V 1 A adapter and keep the serial wires short.

Ideas to Extend

  • Log the JSON data every minute to Google Sheets or InfluxDB and plot daily usage.
  • Add a relay to switch off the load automatically when power goes above a limit.
  • Use several PZEM modules with different Modbus addresses to monitor each circuit of the house.

ESP32 Capacitive Touch Lamp Switch with Relay

ESP32 capacitive touch lamp switch wiring with touch plate, relay module and lamp

Build an ESP32 capacitive touch lamp switch using the built-in touch pin, a metal plate and a relay module. Tap to toggle, long press for off. Wiring table, diagram and full code.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUESP32 DevKit
  • Parts7 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 touch lamp switch turns any metal surface into a light switch. Tap a small metal plate and the lamp turns on, tap it again and it turns off. There is no separate touch sensor module: the ESP32 has capacitive touch sensing built into some of its pins, so the only parts you need are the board, a relay module and a piece of metal.

It is a small beginner project that teaches how the ESP32 touch pins work, how to calibrate them, and how to debounce a touch input so the lamp does not flicker.

ESP32 capacitive touch lamp switch wiring with touch plate, relay module and lamp

How the ESP32 Touch Lamp Switch Works

  • Capacitive sensing: GPIO4 is touch pad T0. The ESP32 measures how much charge the pin and the wire attached to it can hold. When your finger touches the plate, your body adds capacitance and the reading from touchRead() drops noticeably on the original ESP32.
  • Auto calibration: at power-up the sketch takes 20 readings with nobody touching the plate and stores the average as the baseline. A touch is counted when the reading falls 30% below that baseline, so it works with different plate sizes and wire lengths.
  • Debounce: a touch must stay stable for 60 ms before it counts, which filters out electrical noise.
  • Tap and long press: a short tap toggles the lamp when you lift your finger. Holding the plate for 1.5 seconds always turns the lamp OFF.
  • Relay output: GPIO26 drives the relay module, and the relay contacts switch the lamp. The on-board blue LED on GPIO2 shows whether the lamp is on.

Components Required

  • ESP32 DevKit V1 (ESP32-WROOM-32) – 1
  • 1-channel 5 V relay module (opto-isolated, contacts rated 10 A 250 V) – 1
  • Metal touch plate: a coin, a small aluminium or copper sheet, or a steel bolt head – 1
  • Insulated hook-up wire (keep the touch wire under about 30 cm)
  • 5 V USB adapter and USB cable
  • Table lamp with a bulb, and a closed plastic enclosure for the relay
  • Jumper wires and a breadboard

Wiring Table

PartESP32 pinNotes
Touch plateGPIO4 (T0)Single insulated wire, solder it to the plate
Relay module INGPIO26Lamp control signal
Relay module VCCVIN (5V)5 V from USB
Relay module GNDGNDCommon ground
Relay COMLamp live wire (from mains)Switched side
Relay NOLamp live wire (to lamp)Lamp ON when relay is ON
On-board LEDGPIO2Already on the board, no wiring needed

Most cheap relay modules switch ON when the input is LOW, and the sketch is set for that (RELAY_ACTIVE_LOW = true). If your module switches ON with a HIGH input, change it to false. If the relay does not click reliably with the 3.3 V signal, use a module marked as 3.3 V compatible.

Connection Diagram

The illustration at the top shows the general layout. The pin-accurate drawing below matches the wiring table exactly.

ESP32 Capacitive Touch Lamp Switch – Pin-Accurate Wiring ESP32 DevKit GPIO4 (T0) Metal touch plate (insulated wire, keep under 30 cm) GPIO26 Relay module IN VIN (5V) Relay module VCC GND Relay module GND GPIO2 On-board LED (already fitted, shows lamp state) Relay COM and NO are wired in series with the lamp live wire. Mains wiring must be enclosed and done by a qualified person. Power the ESP32 from USB 5 V so the VIN pin can feed the relay module.
Pin-accurate connection diagram for the ESP32 capacitive touch lamp switch.

Arduino Code

In the Arduino IDE install the ESP32 board package by Espressif, select ESP32 Dev Module and upload the sketch. No extra libraries are needed. Keep your hands away from the touch plate for the first second after power-up while it calibrates.

/*
  ESP32 Capacitive Touch Lamp Switch with Relay
  ---------------------------------------------
  Touch a metal plate wired to GPIO4 (touch pad T0) to toggle a lamp
  through a relay module. A short tap toggles the lamp, a long press
  (over 1.5 s) turns it OFF. The on-board LED (GPIO2) mirrors the lamp state.
  No extra touch sensor module is needed: the ESP32 has capacitive touch built in.

  Board: ESP32 Dev Module (ESP32 Arduino core 2.x or 3.x)
*/

const int TOUCH_PIN = 4;     // T0 = GPIO4, connect to the metal touch plate
const int RELAY_PIN = 26;    // relay module IN
const int LED_PIN   = 2;     // on-board blue LED

// Most cheap relay modules turn ON when IN is LOW. Set to false if yours turns ON with HIGH.
const bool RELAY_ACTIVE_LOW = true;

const unsigned long DEBOUNCE_MS   = 60;    // touch must be stable this long
const unsigned long LONG_PRESS_MS = 1500;  // hold this long to force OFF

uint32_t baseline = 0;       // untouched reading, measured at start-up
uint32_t threshold = 0;      // readings past this count as a touch
bool lampOn = false;
bool touched = false;        // debounced touch state
bool longDone = false;       // long press already handled
unsigned long changeStart = 0;
unsigned long pressStart = 0;

void setLamp(bool on) {
  lampOn = on;
  digitalWrite(RELAY_PIN, (on ^ RELAY_ACTIVE_LOW) ? HIGH : LOW);
  digitalWrite(LED_PIN, on ? HIGH : LOW);
  Serial.printf("Lamp %s\n", on ? "ON" : "OFF");
}

// Average several readings to reduce noise
uint32_t readTouch() {
  uint32_t sum = 0;
  for (int i = 0; i < 8; i++) sum += touchRead(TOUCH_PIN);
  return sum / 8;
}

// On the original ESP32 a touch makes the reading DROP.
// (On ESP32-S2/S3 it RISES, so this check handles both.)
bool isTouched(uint32_t v) {
  if (threshold < baseline) return v < threshold;
  return v > threshold;
}

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  setLamp(false);

  delay(500);                       // keep hands off the plate during calibration
  uint32_t sum = 0;
  for (int i = 0; i < 20; i++) { sum += readTouch(); delay(20); }
  baseline = sum / 20;
#if CONFIG_IDF_TARGET_ESP32
  threshold = baseline * 70 / 100;  // ESP32: touched when reading falls 30%
#else
  threshold = baseline * 130 / 100; // ESP32-S2/S3: touched when reading rises 30%
#endif
  Serial.printf("Touch baseline %u, threshold %u\n", baseline, threshold);
}

void loop() {
  uint32_t v = readTouch();
  bool raw = isTouched(v);
  unsigned long now = millis();

  // Debounce: accept a new state only after it stays the same for DEBOUNCE_MS
  if (raw != touched) {
    if (changeStart == 0) changeStart = now;
    if (now - changeStart >= DEBOUNCE_MS) {
      touched = raw;
      changeStart = 0;
      if (touched) {                // finger just landed
        pressStart = now;
        longDone = false;
      } else if (!longDone) {       // finger lifted after a short tap
        setLamp(!lampOn);
      }
    }
  } else {
    changeStart = 0;
  }

  // Long press: force the lamp OFF once
  if (touched && !longDone && now - pressStart >= LONG_PRESS_MS) {
    longDone = true;
    setLamp(false);
  }

  delay(10);
}

Setup and Testing

  • Upload the sketch and open the Serial Monitor at 115200 baud. It prints the baseline and threshold values.
  • Tap the plate and check that the Serial Monitor shows Lamp ON and Lamp OFF, and that the blue LED follows.
  • Test the relay with a low-voltage load or listen for the click before connecting the real lamp.
  • If touches are missed, change 70 to 80 in the threshold line. If it triggers by itself, change it to 60.

Troubleshooting

ProblemFix
Lamp toggles on its ownShorten the touch wire, keep it away from the mains wires, and lower the threshold percentage.
Touch is not detectedMake sure the wire is on GPIO4, not another pin, and that you did not touch the plate during calibration.
Relay works the opposite wayChange RELAY_ACTIVE_LOW in the sketch.
Relay clicks but the lamp does not lightCheck that you used the COM and NO terminals, not NC.
Readings are always 0 or very lowThe plate may be touching a grounded metal case. Insulate it from other metal.

Safety Note

The lamp runs on 230 V mains. Keep the relay and all mains wiring inside a closed box, use a relay rated for the load, and get help from a qualified electrician. The touch plate is connected only to the low-voltage ESP32, never to the mains side.

Ideas to Extend

  • Use two more touch pins for brightness up and down with a MOSFET LED driver instead of a relay.
  • Add Wi-Fi and a web page so the lamp can also be switched from your phone.
  • Hide the touch plate under a thin wooden or plastic table top for an invisible switch.
  • Add an auto-off timer that turns the lamp off after 30 minutes.

ESP32 Smart Home Security System with PIR, Magnetic Door Sensor, OLED, Buzzer and Wi-Fi Alerts

Illustrated wiring overview of an ESP32 DevKit connected to an SSD1306 OLED, HC-SR501 PIR sensor, magnetic reed switch, buzzer, red and green LEDs, arm/disarm button and a 5V relay module

Build an ESP32 home security system with a PIR motion sensor, magnetic door switch, OLED status display, buzzer, relay siren and a local Wi-Fi dashboard to arm, disarm and view events.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUESP32 DevKit
  • Parts12 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 home security system watches a room with a PIR motion sensor and a magnetic door (reed) switch, shows the status on an OLED display, and raises a local alarm with a buzzer, a red LED and an optional 5 V relay for a siren or lamp. You arm and disarm it from a push button or from a small Wi-Fi web page served by the ESP32, so you do not need a cloud account or a phone app.

It is a big combination project: sensing, a timed entry/exit delay, a local siren, an on-device display and a browser dashboard all run on one ESP32 DevKit. The local alarm still works if Wi-Fi is down. Replace the Wi-Fi placeholders in the sketch before you upload it.

How the ESP32 Home Security System Works

  • Arming: press the button or open the /arm page. A 10-second exit delay starts so you can leave without setting the alarm off. The buzzer chirps and the OLED shows EXIT DELAY.
  • Armed and idle: the green LED stays on. The PIR and the reed switch are watched in the main loop.
  • Door opened while armed: an 8-second entry delay starts so you can disarm after coming home. If you do not disarm in time, the alarm sounds.
  • Motion while armed: the alarm starts at once (no entry delay), because movement inside usually means an intruder, not the owner at the door.
  • Alarm: the active buzzer, the red LED and the relay turn on for 30 seconds, then go quiet. The system stays armed until you disarm it.
  • Disarm: press the button again or open /disarm. The siren stops immediately.
  • OLED and web page: both show ARMED, DISARMED, EXIT DELAY, ENTRY DELAY or ALARM, plus motion, door state and the ESP32’s IP address. The page also lists the last 10 events.
  • Reed logic: GPIO32 uses the internal pull-up. When the door is shut the magnet closes the switch, so the pin reads LOW. An open door lets the pin float HIGH.

Components Required

  • ESP32 DevKit (ESP32-WROOM-32) – 1
  • SSD1306 128×64 OLED display (I2C, 4-pin) – 1
  • HC-SR501 PIR motion sensor – 1
  • Magnetic reed switch / door-window sensor – 1
  • Active buzzer, 3.3 V (or a 5 V buzzer driven through a 2N2222 transistor) – 1
  • 5 V single-channel relay module (for a siren or lamp) – 1
  • 5 mm red LED and 5 mm green LED – 1 each
  • 220 Ω resistors – 2
  • Tactile push button – 1
  • Breadboard and jumper wires
  • USB cable and a 5 V 2 A adapter (recommended if the relay drives a siren)
  • Optional: 5–12 V siren or lamp wired to the relay COM and NO terminals

Wiring Table (Pin-to-Pin)

PartPinESP32 PinNotes
SSD1306 OLEDVCC3V3Do not feed the OLED from 5 V
SSD1306 OLEDGNDGNDCommon ground
SSD1306 OLEDSDAGPIO21Default ESP32 I2C data
SSD1306 OLEDSCLGPIO22Default ESP32 I2C clock
HC-SR501 PIRVCCVIN (5V)The module expects 5 V
HC-SR501 PIRGNDGND
HC-SR501 PIROUTGPIO27HIGH when motion is seen; the output is 3.3 V-safe
Reed switchLeg 1GPIO32INPUT_PULLUP in code
Reed switchLeg 2GNDLOW means the door is closed
Active buzzer+GPIO26Use a 3.3 V buzzer, or a transistor for a 5 V one
Active buzzer−GND
Red LEDAnode via 220 ΩGPIO18Alarm indicator
Red LEDCathodeGND
Green LEDAnode via 220 ΩGPIO19On when the system is armed and idle
Green LEDCathodeGND
Push buttonLeg 1GPIO33Internal pull-up; no extra 10 kΩ is required
Push buttonLeg 2GND
Relay moduleVCCVIN (5V)
Relay moduleGNDGND
Relay moduleINGPIO23Most boards are active LOW; see RELAY_ACTIVE_LOW in the code

Connection Diagram

The illustration below is also the featured image and gives a quick view of the layout. Some of its extra resistor labels are artistic and not exact, so wire the circuit using the pin-accurate drawing under it, which matches the wiring table.

Illustrated wiring overview of an ESP32 DevKit connected to an SSD1306 OLED, HC-SR501 PIR sensor, magnetic reed switch, buzzer, red and green LEDs, arm/disarm button and a 5V relay module
Overview: ESP32 DevKit wired to an OLED, PIR, reed switch, buzzer, LEDs, arm/disarm button and relay.
ESP32 Smart Home Security System – Pin-Accurate Wiring ESP32 DevKit 3V3 GND VIN (5V) GPIO21 SDA GPIO22 SCL GPIO27 PIR GPIO32 REED GPIO26 BUZ GPIO18 RED GPIO19 GRN GPIO33 BTN GPIO23 RLY SSD1306 OLED 128 x 64 I2C VCC GND SDA SCL addr 0x3C HC-SR501 PIR VCC OUT GND HIGH = motion Magnetic reed switch Door closed = pin LOW Door open = pin HIGH Active buzzer 3.3 V + to GPIO26 − to GND Red LED + 220 Ω GPIO18 → resistor → anode Cathode → GND Green LED + 220 Ω GPIO19 → resistor → anode Cathode → GND Arm / Disarm button GPIO33 → button → GND Internal pull-up, no 10 kΩ needed 5 V relay module VCC=VIN GND=GND IN = GPIO23 Active LOW (default) Power: USB 5 V into the ESP32. PIR VCC and relay VCC go to VIN (5 V). OLED VCC goes to 3V3 only. Common GND: tie every module ground to an ESP32 GND pin. Reed: one leg to GPIO32 (INPUT_PULLUP), other leg to GND. Magnet present (door shut) reads LOW. Relay load (siren or lamp) connects to the NO and COM screw terminals, not to the ESP32 pins. The illustration above is artistic. Use this drawing and the wiring table for the real pin numbers.
Pin-accurate connection diagram for the ESP32 home security system.

Arduino Code

In the Arduino IDE install the esp32 board package by Espressif, then choose ESP32 Dev Module. From the Library Manager install Adafruit SSD1306 and Adafruit GFX Library (Adafruit BusIO is pulled in automatically). Replace YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD with your 2.4 GHz network details. The sketch was compile-tested with the ESP32 Arduino core; it uses about 73% of flash on a WROOM-32.

/*
 * ESP32 Smart Home Security System
 * Project 17 — ArduinoProjectHub
 *
 * Combines a PIR motion sensor, a magnetic door reed switch, an OLED
 * status display, a local buzzer/LED/relay alarm, an arm/disarm button
 * and a small Wi-Fi web dashboard.
 *
 * Libraries (Library Manager):
 *   - Adafruit SSD1306
 *   - Adafruit GFX Library
 *   - Adafruit BusIO  (installed automatically with the two above)
 *
 * Board: ESP32 Dev Module (or any ESP32-WROOM DevKit)
 * Replace YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD before uploading.
 */

#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// ---------- Wi-Fi placeholders (edit these two lines) ----------
const char* WIFI_SSID     = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

// ---------- Pin map (ESP32 DevKit V1) ----------
const int PIN_SDA       = 21;   // OLED I2C data
const int PIN_SCL       = 22;   // OLED I2C clock
const int PIN_PIR       = 27;   // HC-SR501 OUT (HIGH = motion)
const int PIN_REED      = 32;   // Reed switch to GND (LOW = door closed)
const int PIN_BUZZER    = 26;   // Active 3.3 V buzzer (+)
const int PIN_LED_RED   = 18;   // Alarm LED via 220 ohm
const int PIN_LED_GREEN = 19;   // Armed / ready LED via 220 ohm
const int PIN_BUTTON    = 33;   // Arm/disarm button to GND
const int PIN_RELAY     = 23;   // Relay module IN (siren / lamp)

// Most cheap 5 V relay boards with an optocoupler are active-LOW.
// Set this to 0 if your module turns ON when IN is HIGH.
const bool RELAY_ACTIVE_LOW = true;

const int SCREEN_W = 128;
const int SCREEN_H = 64;
const int OLED_ADDR = 0x3C;

const unsigned long EXIT_DELAY_MS   = 10000;  // time to leave after arming
const unsigned long ENTRY_DELAY_MS  = 8000;   // time to disarm after door opens
const unsigned long ALARM_HOLD_MS   = 30000;  // siren duration
const unsigned long BUTTON_DEBOUNCE = 400;
const unsigned long OLED_PERIOD_MS  = 250;

Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);
WebServer server(80);

bool armed        = false;
bool alarmOn      = false;
bool exitPending  = false;
bool entryPending = false;

unsigned long exitStart   = 0;
unsigned long entryStart  = 0;
unsigned long alarmStart  = 0;
unsigned long lastButton  = 0;
unsigned long lastOled    = 0;
unsigned long lastChirp   = 0;

int lastPir  = LOW;
int lastReed = LOW;   // LOW means closed with INPUT_PULLUP

const int EVENT_MAX = 10;
String eventLog[EVENT_MAX];
int eventCount = 0;

void addEvent(const String& msg) {
  // Newest event sits at index 0.
  for (int i = EVENT_MAX - 1; i > 0; i--) {
    eventLog[i] = eventLog[i - 1];
  }
  unsigned long sec = millis() / 1000UL;
  eventLog[0] = String(sec) + "s: " + msg;
  if (eventCount < EVENT_MAX) eventCount++;
  Serial.println(eventLog[0]);
}

void writeRelay(bool on) {
  if (RELAY_ACTIVE_LOW) {
    digitalWrite(PIN_RELAY, on ? LOW : HIGH);
  } else {
    digitalWrite(PIN_RELAY, on ? HIGH : LOW);
  }
}

void setAlarm(bool on) {
  alarmOn = on;
  digitalWrite(PIN_BUZZER, on ? HIGH : LOW);
  digitalWrite(PIN_LED_RED, on ? HIGH : LOW);
  writeRelay(on);
  if (on) {
    alarmStart = millis();
    entryPending = false;
  }
}

void armSystem(bool on) {
  if (on) {
    armed = true;
    exitPending = true;
    exitStart = millis();
    entryPending = false;
    setAlarm(false);
    addEvent("System ARMED (exit delay)");
  } else {
    armed = false;
    exitPending = false;
    entryPending = false;
    setAlarm(false);
    addEvent("System DISARMED");
  }
}

bool doorIsOpen() {
  // INPUT_PULLUP: magnet present (door closed) pulls the pin LOW.
  return digitalRead(PIN_REED) == HIGH;
}

bool motionDetected() {
  return digitalRead(PIN_PIR) == HIGH;
}

String stateLabel() {
  if (alarmOn)     return "ALARM";
  if (!armed)      return "DISARMED";
  if (exitPending) return "EXIT DELAY";
  if (entryPending)return "ENTRY DELAY";
  return "ARMED";
}

void updateOled(bool motion, bool doorOpen) {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("ESP32 Security");

  display.setTextSize(2);
  display.setCursor(0, 14);
  display.println(stateLabel());

  display.setTextSize(1);
  display.setCursor(0, 36);
  display.print("Motion: ");
  display.println(motion ? "YES" : "no");
  display.print("Door:   ");
  display.println(doorOpen ? "OPEN" : "closed");

  display.setCursor(0, 56);
  if (WiFi.status() == WL_CONNECTED) {
    display.print(WiFi.localIP());
  } else {
    display.print("Wi-Fi offline");
  }
  display.display();
}

void handleRoot() {
  bool motion = motionDetected();
  bool doorOpen = doorIsOpen();
  String st = stateLabel();
  String color = alarmOn ? "#f44336" : (armed ? "#4caf50" : "#9e9e9e");

  String html;
  html.reserve(2500);
  html += F("<!DOCTYPE html><html><head><meta charset='UTF-8'>");
  html += F("<meta name='viewport' content='width=device-width,initial-scale=1'>");
  html += F("<meta http-equiv='refresh' content='4'>");
  html += F("<title>ESP32 Home Security</title><style>");
  html += F("body{font-family:Arial,sans-serif;max-width:480px;margin:24px auto;");
  html += F("padding:0 12px;background:#111;color:#eee}");
  html += F("h1{font-size:22px} .card{background:#1e1e1e;border-radius:12px;");
  html += F("padding:16px;margin:12px 0} .st{font-size:28px;font-weight:bold}");
  html += F("a.btn{display:inline-block;padding:12px 22px;margin:8px 8px 0 0;");
  html += F("border-radius:8px;color:#fff;text-decoration:none}");
  html += F(".arm{background:#2e7d32} .disarm{background:#c62828}");
  html += F("td{padding:6px 0;border-bottom:1px solid #333} table{width:100%}");
  html += F("</style></head><body><h1>ESP32 Home Security</h1>");
  html += "<div class='card'><div class='st' style='color:" + color + "'>" + st + "</div>";
  html += "<p>Motion: <b>";
  html += motion ? "YES" : "no";
  html += "</b><br>Door: <b>";
  html += doorOpen ? "OPEN" : "closed";
  html += "</b><br>IP: ";
  html += WiFi.localIP().toString();
  html += "</p>";
  html += F("<a class='btn arm' href='/arm'>Arm</a>");
  html += F("<a class='btn disarm' href='/disarm'>Disarm</a></div>");
  html += F("<div class='card'><h2>Recent events</h2><table>");
  if (eventCount == 0) {
    html += F("<tr><td>No events yet</td></tr>");
  } else {
    for (int i = 0; i < eventCount; i++) {
      html += "<tr><td>";
      html += eventLog[i];
      html += "</td></tr>";
    }
  }
  html += F("</table></div>");
  html += F("<p>Page refreshes every 4 seconds.</p></body></html>");
  server.send(200, "text/html", html);
}

void handleArm() {
  armSystem(true);
  server.sendHeader("Location", "/");
  server.send(303);
}

void handleDisarm() {
  armSystem(false);
  server.sendHeader("Location", "/");
  server.send(303);
}

void handleStatus() {
  String json = "{";
  json += "\"state\":\"" + stateLabel() + "\",";
  json += "\"armed\":";
  json += armed ? "true" : "false";
  json += ",\"alarm\":";
  json += alarmOn ? "true" : "false";
  json += ",\"motion\":";
  json += motionDetected() ? "true" : "false";
  json += ",\"doorOpen\":";
  json += doorIsOpen() ? "true" : "false";
  json += "}";
  server.send(200, "application/json", json);
}

void setup() {
  Serial.begin(115200);
  delay(200);

  pinMode(PIN_PIR, INPUT);
  pinMode(PIN_REED, INPUT_PULLUP);
  pinMode(PIN_BUZZER, OUTPUT);
  pinMode(PIN_LED_RED, OUTPUT);
  pinMode(PIN_LED_GREEN, OUTPUT);
  pinMode(PIN_BUTTON, INPUT_PULLUP);
  pinMode(PIN_RELAY, OUTPUT);

  digitalWrite(PIN_BUZZER, LOW);
  digitalWrite(PIN_LED_RED, LOW);
  digitalWrite(PIN_LED_GREEN, LOW);
  writeRelay(false);

  Wire.begin(PIN_SDA, PIN_SCL);
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println("SSD1306 not found. Check I2C wiring (0x3C).");
  }
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println("ESP32 Security");
  display.println("Connecting Wi-Fi");
  display.display();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - start < 20000UL) {
    delay(300);
    Serial.print(".");
  }
  Serial.println();
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("Wi-Fi failed. Local alarm still works.");
  }

  server.on("/", handleRoot);
  server.on("/arm", handleArm);
  server.on("/disarm", handleDisarm);
  server.on("/status", handleStatus);
  server.begin();

  addEvent("System boot");
  lastReed = digitalRead(PIN_REED);
  lastPir  = digitalRead(PIN_PIR);
}

void loop() {
  server.handleClient();

  // Arm / disarm from the physical button (active LOW).
  if (digitalRead(PIN_BUTTON) == LOW && millis() - lastButton > BUTTON_DEBOUNCE) {
    lastButton = millis();
    armSystem(!armed);
  }

  bool motion   = motionDetected();
  bool doorOpen = doorIsOpen();

  if (motion && lastPir == LOW) {
    addEvent("Motion detected");
  }
  if (doorOpen && lastReed == LOW) {
    addEvent("Door opened");
  }
  if (!doorOpen && lastReed == HIGH) {
    addEvent("Door closed");
  }
  lastPir  = motion ? HIGH : LOW;
  lastReed = doorOpen ? HIGH : LOW;

  // Finish the exit delay so the owner can walk out after arming.
  if (exitPending && millis() - exitStart >= EXIT_DELAY_MS) {
    exitPending = false;
    addEvent("Exit delay finished");
  }

  // Triggers only when armed, not alarming, and not in the exit window.
  if (armed && !alarmOn && !exitPending) {
    if (motion) {
      setAlarm(true);
      addEvent("ALARM: motion");
    } else if (doorOpen && !entryPending) {
      entryPending = true;
      entryStart = millis();
      addEvent("Entry delay started");
    }
    if (entryPending && millis() - entryStart >= ENTRY_DELAY_MS) {
      entryPending = false;
      setAlarm(true);
      addEvent("ALARM: door");
    }
  }

  if (!armed) {
    entryPending = false;
  }

  // Auto-silence the siren after ALARM_HOLD_MS. System stays armed.
  if (alarmOn && millis() - alarmStart >= ALARM_HOLD_MS) {
    setAlarm(false);
    addEvent("Alarm timed out");
  }

  // Soft chirp during entry / exit delays so you know the timer is running.
  if ((entryPending || exitPending) && !alarmOn) {
    if (millis() - lastChirp > 400) {
      lastChirp = millis();
      digitalWrite(PIN_BUZZER, !digitalRead(PIN_BUZZER));
    }
  } else if (!alarmOn) {
    digitalWrite(PIN_BUZZER, LOW);
  }

  // Green LED: armed and idle (not alarming).
  digitalWrite(PIN_LED_GREEN, (armed && !alarmOn) ? HIGH : LOW);

  if (millis() - lastOled >= OLED_PERIOD_MS) {
    lastOled = millis();
    updateOled(motion, doorOpen);
  }
}

Code Explained

  • armSystem(true) starts a 10-second exit delay so you can walk out after arming. Motion and the door are ignored until that window ends.
  • An open door while armed starts ENTRY_DELAY_MS (8 seconds). Motion skips that delay and calls setAlarm(true) immediately.
  • setAlarm() drives the buzzer, the red LED and the relay together. After 30 seconds the siren times out, but the system stays armed.
  • RELAY_ACTIVE_LOW matches the common optocoupler relay boards. If your siren turns on when the system is idle, set it to false.
  • The built-in WebServer library serves / (the dashboard), /arm, /disarm and /status (a small JSON feed you can poll from another sketch or a home dashboard).
  • Event strings are stored in a 10-slot list with the newest first, and shown both on the Serial monitor and on the web page.

Testing the Project

  1. Upload the sketch, open Serial at 115200 baud and copy the IP address (it is also on the OLED).
  2. With the system disarmed, wave your hand in front of the PIR. The OLED should say Motion: YES and the web event list should add “Motion detected”. The siren must stay off.
  3. Open and close the door. The OLED should switch between OPEN and closed.
  4. Press the button or visit http://<ip>/arm. You should hear chirps during the 10-second exit delay.
  5. After the delay, wave at the PIR. The buzzer, red LED and relay should turn on. Disarm from the button or the web page to silence them.
  6. Arm again, wait for the exit delay, then open the door. You get 8 seconds of chirps to disarm before the full alarm.

Troubleshooting

ProblemFix
OLED stays blackCheck SDA/SCL are not swapped, power the display from 3V3, and try I2C address 0x3D if 0x3C fails.
PIR is always HIGHGive it 30 to 60 seconds to warm up, then turn the sensitivity pot down. Keep it away from heaters and windows.
Door always reads OPENMove the magnet closer to the reed body when the door is shut. The code expects a closed circuit (LOW) with the door closed.
Relay is on when idleYour module is the other polarity. Set RELAY_ACTIVE_LOW to false and upload again.
Web page will not loadUse a 2.4 GHz Wi-Fi network (the ESP32 cannot join 5 GHz), and open the IP shown on the OLED. Phone data will not reach a local IP.
Board resets when the siren firesPower the ESP32 from a strong 5 V 2 A USB adapter and keep high-current siren wiring on the relay contacts only.
Wi-Fi fails but you still want an alarmThat is expected. The button, sensors, OLED and siren keep working without a network.

Ideas to Extend This Project

  • Add a second reed switch on a window and treat either open contact as an entry event.
  • Send a Telegram or email alert from the ESP32 when the alarm starts (still keep the local siren).
  • Store the armed state in NVS so a short power cut does not disarm the system.
  • Add an MQ-2 smoke or gas sensor as a separate fire zone that alarms even when the system is disarmed.
  • Put the web page behind a simple password or serve it only on your home network through a reserved DHCP address.

FAQ

Do I need the internet, or only my router? Only your local Wi-Fi. The dashboard never leaves your home network, and there is no cloud login.

Can I skip the relay? Yes. The buzzer and red LED are enough for a bench test. Add the relay when you want a louder siren or a lamp.

Will this work on an ESP32-S3 or ESP32-C3? Yes, after you change the pin numbers to match that board and confirm the I2C pins in Wire.begin().

Is the generated picture exact? No. Use it as a layout overview. The SVG diagram and the wiring table are the pin-accurate references, including the internal pull-up on the button (no extra 10 kΩ resistor).

ESP32 RFID Door Lock with RC522 & OLED

Wiring diagram of an ESP32 RFID door lock with RC522 reader, SSD1306 OLED, 5 V relay module, 12 V solenoid, buzzer and LEDs

Build an ESP32 RFID door lock with an RC522 reader, OLED, relay and buzzer. Wiring table, connection diagram and full commented Arduino code.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUESP32 DevKit
  • Parts12 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This ESP32 RFID door lock reads a MIFARE keyfobon an RC522 (MFRC522) reader, checks the card UID against a short list in the sketch, and unlocks a 12 V solenoid through a relay for five seconds. A 0.96" SSD1306 OLED shows ACCESS GRANTED or ACCESS DENIED, a green or red LED lights to match, and an active buzzer gives a short double-beep or a longer reject tone.

It is a medium, beginner-friendly access-control build: one ESP32 DevKit, an RC522, an I2C OLED, a 5 V relay module and a lock. There is no Wi-Fi in the basic sketch, so the lock keeps working if your router is down. Use it on a cupboard, a drawer, a cabinet or a low-voltage door strike while you learn SPI, I2C and relay switching.

This is a learning project, not a certified security lock. Cheap MIFARE Classic UIDs can be copied, so do not use it as the only lock on an exterior house door.

How the ESP32 RFID Door Lock Works

The RC522 talks to the ESP32 over SPI. When you hold a card near the antenna, the chip sends the card’s UID (usually four bytes on a typical keyfob). The sketch compares those first four bytes with the AUTH_UIDS list you typed in after reading the Serial Monitor.

  • Match: the OLED shows ACCESS GRANTED and OPEN, the green LED lights, the buzzer beeps twice, and GPIO26 pulls the relay IN pin low. The relay contacts feed 12 V to the solenoid for five seconds, then the lock closes again.
  • No match: the OLED shows ACCESS DENIED, the red LED lights and the buzzer sounds three longer beeps. The relay stays off.

The OLED uses the ESP32’s default I2C pins, GPIO21 (SDA) and GPIO22 (SCL). SPI uses the VSPI pins: GPIO18 (SCK), GPIO23 (MOSI), GPIO19 (MISO), with GPIO5 as chip-select (the pin labelled SDA on the RC522) and GPIO4 as reset.

Power is split on purpose. The RC522 and the OLED must run from 3.3 V — 5 V will often kill an RC522. The relay module takes 5 V on VCC from the ESP32 VIN pin (the same 5 V that USB supplies). The solenoid has its own 12 V adapter. Join the 12 V negative to the ESP32 GND so the relay coil and contacts share a common ground.

Components Required

  • ESP32 DevKit V1 (30-pin DOIT board or similar) – 1
  • RC522 RFID reader module (MFRC522, 13.56 MHz) – 1
  • MIFARE Classic 1K cards or keyfobs – 2 or more
  • 0.96" SSD1306 I2C OLED (128×64) – 1
  • 5 V relay module, optocoupler type, one channel – 1
  • 12 V solenoid lock or fail-secure door strike – 1
  • 12 V DC adapter sized for the lock (often 1 A or more) – 1
  • Active buzzer, 3.3 V (or a buzzer module with an I/O pin) – 1
  • LEDs: green and red, 5 mm – 1 each
  • 330 Ω resistors – 2
  • Jumper wires and a breadboard
  • USB cable for the ESP32 (also supplies 5 V to VIN)

Wiring Table (Pin-to-Pin)

PartPart PinESP32 PinNotes
RC5223.3V3V33.3 V only. Do not use VIN or 5 V
RC522GNDGNDCommon ground
RC522RSTGPIO4Reader reset
RC522SDA (SS / NSS)GPIO5SPI chip-select. This pad is labelled SDA on most RC522 boards
RC522SCKGPIO18VSPI clock
RC522MOSIGPIO23ESP32 data out
RC522MISOGPIO19ESP32 data in
RC522IRQnot connectedLeave open
OLED SSD1306VCC3V33.3 V
OLED SSD1306GNDGNDCommon ground
OLED SSD1306SCLGPIO22Default I2C clock
OLED SSD1306SDAGPIO21Default I2C data
Relay moduleVCCVIN (5 V)Coil / optocoupler supply from USB 5 V
Relay moduleGNDGNDCommon ground
Relay moduleINGPIO26Active LOW on most modules: LOW = unlock
Relay contactsCOM+12 V adapter +Switched lock supply
Relay contactsNOSolenoid +Normally open, so the lock is off until a valid card
Solenoid−12 V adapter −Join this negative to ESP32 GND
Active buzzer+GPIO25HIGH = beep. Use a transistor for a loud 5 V buzzer
Active buzzer−GNDCommon ground
Green LEDAnode through 330 ΩGPIO27Access granted
Green LEDCathodeGNDCommon ground
Red LEDAnode through 330 ΩGPIO14Access denied. GPIO14 is safe after boot
Red LEDCathodeGNDCommon ground

Do not wire anything to GPIO0, GPIO2 or GPIO12 if you can avoid it — those pins affect how the ESP32 boots. GPIO6 to GPIO11 are used by the flash chip and must stay unused. The pins in the table above stay clear of both problems.

If your relay module has a separate JD-VCC jumper, you can remove the jumper and feed 5 V into JD-VCC while VCC stays at 3.3 V. That keeps the optocoupler on 3.3 V logic. With the jumper left in place, VCC on VIN (5 V) and a 3.3 V IN signal still works on most modules.

Connection Diagram

The diagram below matches the wiring table. The generated illustration is the featured image for this post; the labelled drawing under it is the pin-accurate version to build from.

Wiring diagram of an ESP32 RFID door lock with RC522 reader, SSD1306 OLED, 5 V relay module, 12 V solenoid, buzzer and LEDs
ESP32 RFID door lock wiring: RC522, OLED, relay, 12 V solenoid, buzzer and LEDs.
ESP32 RFID Door Lock – Wiring MFRC522 RFID reader (3.3 V only) 3.3VGNDRSTSDASCK MOSI MISO ESP-WROOM ESP32 DevKit V1 USB 5 V 3V3 GPIO4 GPIO5 GPIO18 GPIO23 GPIO19 GND VIN 3V3 GPIO21 GPIO22 GPIO26 GPIO25 GPIO27 GPIO14 GND Scan card OLED 0.96″ SSD1306 VCCGNDSCLSDA coil 5 V relay module IN active LOW VCCGNDIN COMNO 12 V solenoid lock COM → +12 V NO → lock + lock − → 12 V supply GND Active buzzer + − Green 330 Ω Red 330 Ω RC522 3.3V → ESP32 3V3 (not 5 V) RST → GPIO4 SDA → GPIO5 SCK → GPIO18 MOSI → GPIO23 MISO → GPIO19 VCC → 3V3 SCL → GPIO22 SDA → GPIO21 VCC → VIN (5 V) IN → GPIO26 buzzer + → GPIO25 green → GPIO27 red → GPIO14 Common GND Power: RC522 and OLED on 3.3 V only. Relay module VCC on VIN (5 V from USB). Solenoid on a separate 12 V supply, sharing ground with the ESP32. SPI: GPIO5 / 18 / 23 / 19 / 4. I2C OLED: GPIO21 (SDA) and GPIO22 (SCL). Relay IN GPIO26, buzzer GPIO25, green LED GPIO27, red LED GPIO14.
Pin-accurate connection diagram for the ESP32 RFID door lock: RC522 on VSPI (GPIO5, 18, 23, 19, 4), OLED on I2C (GPIO21, 22), relay on GPIO26, buzzer on GPIO25, LEDs on GPIO27 and GPIO14.

Arduino Code for the ESP32

In the Arduino IDE install the esp32 by Espressif Systems board package and choose ESP32 Dev Module. Then install MFRC522 (by GithubCommunity), Adafruit SSD1306 and Adafruit GFX Library from the Library Manager. Upload the sketch, open the Serial Monitor at 115200 baud, scan each card, and paste the printed { 0x.., 0x.., 0x.., 0x.. } line into AUTH_UIDS. Upload once more so those cards are authorised.

/*
  ESP32 RFID Door Lock with MFRC522 RC522 reader and SSD1306 OLED

  Board: "ESP32 Dev Module" (DOIT ESP32 DevKit V1 or similar)
  Libraries (Arduino Library Manager):
    - MFRC522 by GithubCommunity
    - Adafruit SSD1306
    - Adafruit GFX Library

  Scan a card once with the Serial Monitor open at 115200 baud.
  Copy the printed UID bytes into AUTH_UIDS below, then upload again.

  Pin map (VSPI + default I2C):
    RC522 RST  -> GPIO4
    RC522 SDA  -> GPIO5
    RC522 SCK  -> GPIO18
    RC522 MOSI -> GPIO23
    RC522 MISO -> GPIO19
    RC522 3.3V -> 3V3     (never 5 V)
    OLED SDA   -> GPIO21
    OLED SCL   -> GPIO22
    Relay IN   -> GPIO26  (active LOW on most modules)
    Buzzer +   -> GPIO25
    Green LED  -> GPIO27 through 330 ohm
    Red LED    -> GPIO14 through 330 ohm
*/

#include <SPI.h>
#include <MFRC522.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

static const uint8_t RST_PIN     = 4;
static const uint8_t SS_PIN      = 5;    // RC522 SDA / NSS
static const uint8_t RELAY_PIN   = 26;
static const uint8_t BUZZER_PIN  = 25;
static const uint8_t LED_OK_PIN  = 27;   // green = access granted
static const uint8_t LED_NO_PIN  = 14;   // red   = access denied

// Most hobby 5 V relay modules energise the coil when IN is pulled LOW.
static const bool     RELAY_ACTIVE_LOW = true;
static const uint32_t UNLOCK_MS        = 5000;
static const uint32_t SCAN_COOLDOWN_MS = 1200;

static const uint8_t SCREEN_W   = 128;
static const uint8_t SCREEN_H   = 64;
static const uint8_t OLED_ADDR  = 0x3C;  // try 0x3D if the screen stays blank

MFRC522 rfid(SS_PIN, RST_PIN);
Adafruit_SSD1306 display(SCREEN_W, SCREEN_H, &Wire, -1);

// Replace these example UIDs with the ones your cards print in Serial.
// The placeholders below will not match a real keyfob.
const uint8_t AUTH_COUNT = 2;
const uint8_t AUTH_UIDS[AUTH_COUNT][4] = {
  { 0xDE, 0xAD, 0xBE, 0xEF },  // example card 1 — replace me
  { 0x11, 0x22, 0x33, 0x44 }   // example card 2 — replace me
};

uint32_t lastScanMs = 0;

void setUnlocked(bool unlocked) {
  if (RELAY_ACTIVE_LOW) {
    digitalWrite(RELAY_PIN, unlocked ? LOW : HIGH);
  } else {
    digitalWrite(RELAY_PIN, unlocked ? HIGH : LOW);
  }
}

void beep(uint16_t onMs, uint16_t offMs, uint8_t times) {
  for (uint8_t i = 0; i < times; i++) {
    digitalWrite(BUZZER_PIN, HIGH);
    delay(onMs);
    digitalWrite(BUZZER_PIN, LOW);
    if (i + 1 < times) {
      delay(offMs);
    }
  }
}

void showIdle() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println(F("ESP32 RFID Lock"));
  display.drawFastHLine(0, 12, SCREEN_W, SSD1306_WHITE);
  display.setTextSize(2);
  display.setCursor(16, 28);
  display.println(F("Scan card"));
  display.display();
}

void showUidLine(const MFRC522::Uid &uid) {
  display.setTextSize(1);
  display.setCursor(0, 54);
  display.print(F("UID:"));
  uint8_t n = uid.size;
  if (n > 4) {
    n = 4;
  }
  for (uint8_t i = 0; i < n; i++) {
    display.print(' ');
    if (uid.uidByte[i] < 0x10) {
      display.print('0');
    }
    display.print(uid.uidByte[i], HEX);
  }
}

void showResult(bool granted, const MFRC522::Uid &uid) {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.println(granted ? F("ACCESS GRANTED") : F("ACCESS DENIED"));
  display.drawFastHLine(0, 12, SCREEN_W, SSD1306_WHITE);
  display.setTextSize(2);
  display.setCursor(granted ? 28 : 34, 24);
  display.println(granted ? F("OPEN") : F("STOP"));
  showUidLine(uid);
  display.display();
}

void printUid(const MFRC522::Uid &uid) {
  Serial.print(F("UID ("));
  Serial.print(uid.size);
  Serial.print(F(" bytes):"));
  for (uint8_t i = 0; i < uid.size; i++) {
    Serial.print(F(" "));
    if (uid.uidByte[i] < 0x10) {
      Serial.print('0');
    }
    Serial.print(uid.uidByte[i], HEX);
  }
  Serial.println();

  if (uid.size >= 4) {
    Serial.print(F("Copy into AUTH_UIDS as: { "));
    for (uint8_t i = 0; i < 4; i++) {
      Serial.print(F("0x"));
      if (uid.uidByte[i] < 0x10) {
        Serial.print('0');
      }
      Serial.print(uid.uidByte[i], HEX);
      if (i < 3) {
        Serial.print(F(", "));
      }
    }
    Serial.println(F(" }"));
  }
}

bool isAuthorized(const MFRC522::Uid &uid) {
  if (uid.size < 4) {
    return false;
  }
  for (uint8_t i = 0; i < AUTH_COUNT; i++) {
    if (memcmp(uid.uidByte, AUTH_UIDS[i], 4) == 0) {
      return true;
    }
  }
  return false;
}

void setup() {
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_OK_PIN, OUTPUT);
  pinMode(LED_NO_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  digitalWrite(LED_OK_PIN, LOW);
  digitalWrite(LED_NO_PIN, LOW);
  setUnlocked(false);

  Serial.begin(115200);
  delay(200);
  Serial.println(F("ESP32 RFID door lock"));
  Serial.println(F("Scan a card to print its UID, then add it to AUTH_UIDS."));

  SPI.begin();                 // VSPI: SCK=18, MISO=19, MOSI=23
  rfid.PCD_Init();

  Wire.begin(21, 22);          // SDA, SCL
  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println(F("OLED not found at 0x3C. Check wiring or try address 0x3D."));
  }

  showIdle();
}

void loop() {
  if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) {
    return;
  }

  uint32_t now = millis();
  if (now - lastScanMs < SCAN_COOLDOWN_MS) {
    rfid.PICC_HaltA();
    rfid.PCD_StopCrypto1();
    return;
  }
  lastScanMs = now;

  printUid(rfid.uid);
  bool granted = isAuthorized(rfid.uid);
  showResult(granted, rfid.uid);

  if (granted) {
    digitalWrite(LED_OK_PIN, HIGH);
    digitalWrite(LED_NO_PIN, LOW);
    beep(80, 80, 2);
    setUnlocked(true);
    delay(UNLOCK_MS);
    setUnlocked(false);
    digitalWrite(LED_OK_PIN, LOW);
  } else {
    digitalWrite(LED_OK_PIN, LOW);
    digitalWrite(LED_NO_PIN, HIGH);
    beep(350, 120, 3);
    delay(800);
    digitalWrite(LED_NO_PIN, LOW);
  }

  rfid.PICC_HaltA();
  rfid.PCD_StopCrypto1();
  showIdle();
}

How to Build It

  1. Wire the RC522 to 3V3, GND, RST (GPIO4), SDA (GPIO5), SCK (GPIO18), MOSI (GPIO23) and MISO (GPIO19). Double-check that the reader is not on 5 V.
  2. Wire the OLED: VCC to 3V3, GND to GND, SCL to GPIO22, SDA to GPIO21.
  3. Wire the relay module: VCC to VIN, GND to GND, IN to GPIO26.
  4. Connect the 12 V adapter positive to relay COM, relay NO to the solenoid positive, and the solenoid negative to the 12 V adapter negative. Join that negative to an ESP32 GND pin.
  5. Fit the active buzzer on GPIO25 and the two LEDs (green on GPIO27, red on GPIO14) each with a 330 Ω resistor.
  6. Plug the ESP32 into USB, select the right port, and upload the sketch.
  7. Open Serial Monitor at 115200 baud, scan a card, copy its UID into AUTH_UIDS, and upload again.

Testing the Lock

  1. On reset the OLED should say Scan card and the relay should be off (lock closed).
  2. Scan a card that is not yet in the list. The OLED shows ACCESS DENIED, the red LED lights and the buzzer sounds three long beeps. The solenoid must stay locked.
  3. Add that card’s UID to the sketch and upload again.
  4. Scan the same card. You should see ACCESS GRANTED, a double beep, the green LED, and the relay clicking on for five seconds.
  5. Measure the solenoid supply while it is unlocked: it should see about 12 V only during those five seconds.
  6. If the relay clicks the wrong way (on at idle, off for a valid card), set RELAY_ACTIVE_LOW to false and upload again.

Troubleshooting

ProblemFix
RC522 not found / UID never printsConfirm 3.3 V (not 5 V) on the reader, and that SDA went to GPIO5, SCK to 18, MOSI to 23, MISO to 19 and RST to 4. Try a shorter set of Dupont wires.
OLED stays blankSwap SDA and SCL if you may have crossed them. The sketch uses address 0x3C; if your module is 0x3D, change OLED_ADDR.
Relay never clicksCheck VIN has 5 V while USB is plugged in. Confirm IN is on GPIO26. Some modules need the opposite polarity — flip RELAY_ACTIVE_LOW.
Relay clicks but the lock does not moveThe contacts (COM / NO) are separate from the IN pin. Check the 12 V adapter, the solenoid polarity and the common ground.
Every card is deniedYou are still using the example UIDs. Copy the line the Serial Monitor prints into AUTH_UIDS and upload again.
ESP32 will not boot or uploadUnplug GPIO12 if you used it, and remove any wire from EN or GPIO0. Use a data-capable USB cable.
Buzzer is silent or only clicksA passive buzzer needs a tone signal. Use an active buzzer, or a module with its own driver transistor.

Ideas to Extend This Project

  • Store authorised UIDs in ESP32 Preferences (NVS) so you can enrol a card from the Serial Monitor without recompiling.
  • Add a hidden master card that puts the lock into enrol mode for the next scan.
  • Log each attempt to an SD card or, later, to a local web page. If you add Wi-Fi, put YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD in the sketch — never commit real credentials.
  • Drive a fail-secure 12 V door strike in a proper enclosure, with the 12 V wiring kept off the breadboard.
  • Add a mechanical key override or a push-button inside the room so you cannot lock yourself out during testing.

FAQ

Can I power the RC522 from 5 V? No. The MFRC522 is a 3.3 V part. 5 V on the 3.3V pin, or 5 V SPI signals from a 5 V Arduino without level shifters, is a common way to destroy the module. The ESP32 is 3.3 V, so it is a good match.

Will this work with an ESP32-C3 or ESP32-S3 board? Yes, if you change the pin numbers to pins that exist on that board and update SPI.begin() if you leave the default VSPI pins. The rest of the sketch stays the same.

My card prints seven UID bytes. Many NFC tags do. The sketch still compares the first four bytes, which is enough to tell typical cards apart. For a stricter check, extend AUTH_UIDS and memcmp to seven bytes.

Is a cloned card a risk? Yes, on MIFARE Classic. Treat this build as a cupboard lock or a learning demo. A production door needs a reader that uses encrypted mutual authentication, not UID matching alone.

Can I use a magnetic lock instead of a solenoid? A maglock is usually fail-safe (it unlocks when power is removed). Wire it on the relay NC contact so a valid card drops power for five seconds, and understand that a power cut will also unlock the door.

Related Projects

Browse more ESP32 Projects on Arduino Project Hub.