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.

Wemos D1 Mini Wi-Fi Lux Meter with BH1750 & OLED

Connection diagram of the Wemos D1 Mini Wi-Fi lux meter with BH1750 light sensor and SSD1306 OLED on the I2C bus (D1 SCL, D2 SDA) and a hold button on D5

Build a pocket Wi-Fi lux meter with a Wemos D1 Mini, a BH1750 light sensor and a 0.96 inch OLED that shows light level, min/max and a room rating, plus a live phone web page.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts6 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Is your study desk bright enough? Does the plant corner get enough light? Is the workshop bench lit well for soldering? Our eyes adapt so well that we are bad at judging light. This small Wemos D1 Mini lux meter measures light in lux with a BH1750 sensor, shows the reading on a 0.96 inch OLED with a simple rating (Dark, Dim, Living room, Reading, Office / desk, Bright, Direct sun) and keeps the minimum and maximum values. It also hosts a live web page, so you can place the sensor in one spot and read it on your phone from across the room.

It is an easy one-evening build: only three modules on one I2C bus and one push button. The BH1750 is read directly with the Wire library using the commands from its datasheet, so you only need the Adafruit SSD1306 and GFX libraries for the display.

Connection diagram of the Wemos D1 Mini Wi-Fi lux meter with BH1750 light sensor and SSD1306 OLED on the I2C bus (D1 SCL, D2 SDA) and a hold button on D5

How It Works

  • BH1750 light sensor: a digital sensor with a photodiode, amplifier and 16-bit ADC inside. Its spectral response is close to the human eye, so the reading is real lux, from 1 to about 65,000 lx. The sketch powers it on and puts it in continuous high-resolution mode (1 lx steps, about 120 ms per reading).
  • Reading the value: every 500 ms the D1 Mini asks the sensor for two bytes over I2C. The datasheet formula is lux = raw count / 1.2. If the sensor does not answer, the code shows an error and tries to wake it up again.
  • Rating and min/max: the lux value is compared with common indoor light levels (for example about 300–500 lx for reading and 500–1000 lx for desk work) to show a word rating. The lowest and highest readings since the last reset are stored as min and max.
  • Button: a short press toggles HOLD, which freezes the reading so you can move the meter and still read it. A long press (more than 1 second) resets min and max.
  • Wi-Fi web page: the D1 Mini joins your Wi-Fi and serves a page at http://luxmeter.local (or its IP address). The page asks /data once per second for a small JSON reply and shows the lux value, rating, min/max and a log-scale bar, with HOLD and RESET buttons.

Components Required

  • Wemos D1 Mini (ESP8266) board – 1
  • BH1750 (GY-302) digital light sensor module – 1
  • 0.96 inch SSD1306 I2C OLED display, 128×64, 4-pin – 1
  • 6 mm tactile push button – 1
  • Breadboard (400 points) and male-to-male jumper wires – 1 set
  • Micro-USB cable and 5 V USB supply or power bank – 1

Wiring Table

Module pinWemos D1 Mini pinNotes
BH1750 VCC3V3The module also works on 5 V, but 3.3 V keeps the I2C lines at ESP8266 level
BH1750 GNDGNDCommon ground
BH1750 SCLD1 (GPIO5)I2C clock, shared with the OLED
BH1750 SDAD2 (GPIO4)I2C data, shared with the OLED
BH1750 ADDRGNDAddress 0x23 (tie to 3V3 for 0x5C and change BH1750_ADDR in the code)
OLED VCC3V3Check the pin order on your module: some have GND first, some VCC first
OLED GNDGNDCommon ground
OLED SCLD1 (GPIO5)Same I2C bus
OLED SDAD2 (GPIO4)Same I2C bus, address 0x3C
Push button leg 1D5 (GPIO14)Internal pull-up is enabled in the code
Push button leg 2GNDPressed = LOW
Micro-USB5 V USB supplyPowers the board and both modules through the onboard 3.3 V regulator

Connection Diagram

The diagram near the top of this post shows the full layout. The drawing below lists every connection pin by pin and matches the wiring table and the code.

Wemos D1 Mini Lux Meter – Pin-Accurate Wiring Wemos D1 Mini 3V3 BH1750 VCC and OLED VCC GND BH1750 GND, BH1750 ADDR, OLED GND, button leg 2 D1 (GPIO5) SCL BH1750 SCL and OLED SCL D2 (GPIO4) SDA BH1750 SDA and OLED SDA D5 (GPIO14) Push button leg 1 (INPUT_PULLUP) USB 5 V Power from USB supply or power bank BH1750 address 0x23 (ADDR to GND), OLED address 0x3C. Most modules already have I2C pull-up resistors.
Pin-accurate connection diagram for the Wemos D1 Mini Wi-Fi lux meter.

Code

Install the ESP8266 boards package in the Arduino IDE, select LOLIN(WEMOS) D1 R2 & mini, and install Adafruit SSD1306 and Adafruit GFX from the Library Manager. Replace YOUR_WIFI_SSID and YOUR_WIFI_PASSWORD with your own network details before uploading. The meter still works on the OLED without Wi-Fi.

/*
  Wemos D1 Mini Wi-Fi Lux Meter with BH1750 and OLED
  Arduino Project Hub - https://ardiunoprojecthub.online/

  What it does:
  - Reads light level in lux from a BH1750 sensor (I2C, no extra library).
  - Shows lux, a light-level rating, min and max on a 0.96" SSD1306 OLED.
  - A push button on D5: short press = HOLD/RUN, long press (1 s) = reset min/max.
  - Serves a small web page at http://luxmeter.local (or the IP address)
    that refreshes every second from /data (JSON).

  Wiring (see the wiring table in the post):
  BH1750 VCC -> 3V3, GND -> GND, SCL -> D1, SDA -> D2, ADDR -> GND (0x23)
  OLED   VCC -> 3V3, GND -> GND, SCL -> D1, SDA -> D2 (address 0x3C)
  Button one leg -> D5, other leg -> GND (internal pull-up used)

  Libraries: Adafruit SSD1306, Adafruit GFX (Library Manager).
  Board: "LOLIN(WEMOS) D1 R2 & mini" from the ESP8266 boards package.
*/

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// ---------- Wi-Fi settings: replace with your own ----------
const char* WIFI_SSID     = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

// ---------- Pins and addresses ----------
const uint8_t BUTTON_PIN   = D5;    // GPIO14, button to GND
const uint8_t BH1750_ADDR  = 0x23;  // ADDR pin to GND (0x5C if ADDR to 3V3)
const uint8_t OLED_ADDR    = 0x3C;

// BH1750 commands (from the datasheet)
const uint8_t BH_POWER_ON  = 0x01;
const uint8_t BH_RESET     = 0x07;
const uint8_t BH_CONT_HRES = 0x10;  // continuous, 1 lx resolution, ~120 ms

Adafruit_SSD1306 display(128, 64, &Wire, -1);
ESP8266WebServer server(80);

float luxNow = 0, luxMin = 0, luxMax = 0;
bool  holdOn = false;
bool  sensorOk = false;
bool  firstReading = true;
unsigned long lastRead = 0;

// ---------- BH1750 helpers ----------
bool bhCommand(uint8_t cmd) {
  Wire.beginTransmission(BH1750_ADDR);
  Wire.write(cmd);
  return Wire.endTransmission() == 0;      // 0 = sensor answered
}

bool bhBegin() {
  if (!bhCommand(BH_POWER_ON)) return false;
  bhCommand(BH_RESET);
  return bhCommand(BH_CONT_HRES);
}

// Returns lux, or -1 if the sensor did not answer
float bhReadLux() {
  if (Wire.requestFrom(BH1750_ADDR, (uint8_t)2) != 2) return -1;
  uint16_t raw = ((uint16_t)Wire.read() << 8) | Wire.read();
  return raw / 1.2f;                       // datasheet: lux = count / 1.2
}

// ---------- Light-level rating ----------
const char* rating(float lx) {
  if (lx < 10)    return "Dark";
  if (lx < 100)   return "Dim";
  if (lx < 300)   return "Living room";
  if (lx < 500)   return "Reading";
  if (lx < 1000)  return "Office / desk";
  if (lx < 10000) return "Bright / shade";
  return "Direct sun";
}

// ---------- OLED ----------
void drawScreen() {
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print(F("LUX METER"));
  if (holdOn) { display.setCursor(98, 0); display.print(F("HOLD")); }

  display.setCursor(0, 14);
  if (!sensorOk) {
    display.setTextSize(1);
    display.print(F("BH1750 not found"));
  } else {
    display.setTextSize(2);
    display.print(luxNow, luxNow < 100 ? 1 : 0);
    display.setTextSize(1);
    display.print(F(" lx"));
    display.setCursor(0, 34);
    display.print(rating(luxNow));
    display.setCursor(0, 46);
    display.print(F("min ")); display.print(luxMin, 0);
    display.print(F("  max ")); display.print(luxMax, 0);
  }
  display.setCursor(0, 56);
  if (WiFi.status() == WL_CONNECTED) display.print(WiFi.localIP());
  else display.print(F("Wi-Fi offline"));
  display.display();
}

// ---------- Web page ----------
const char PAGE[] PROGMEM = R"HTML(<!DOCTYPE html><html><head>
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Lux Meter</title>
<style>body{font-family:Arial,sans-serif;text-align:center;background:#111;color:#eee}
#lux{font-size:64px;margin:10px}#bar{height:18px;background:#333;border-radius:9px;margin:10px 20px}
#fill{height:18px;width:0;background:#fbc02d;border-radius:9px}button{font-size:18px;margin:6px;padding:8px 16px}</style>
</head><body><h2>Wemos D1 Mini Lux Meter</h2>
<div id="lux">--</div><div id="rate"></div><div id="bar"><div id="fill"></div></div>
<p>Min <b id="mn">-</b> lx &nbsp; Max <b id="mx">-</b> lx</p><p id="hold"></p>
<button onclick="fetch('/hold')">Hold / Run</button><button onclick="fetch('/reset')">Reset min/max</button>
<script>
function upd(){fetch('/data').then(r=>r.json()).then(d=>{
 if(!d.ok){lux.textContent='Sensor error';return;}
 lux.textContent=d.lux+' lx';rate.textContent=d.rating;mn.textContent=d.min;mx.textContent=d.max;
 hold.textContent=d.hold?'HOLD':'';
 // log scale bar: 1 lx = 0%, 100000 lx = 100%
 fill.style.width=Math.min(100,Math.max(0,Math.log10(Math.max(d.lux,1))*20))+'%';});}
setInterval(upd,1000);upd();
</script></body></html>)HTML";

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

void handleData() {
  String j = "{\"ok\":";
  j += sensorOk ? "true" : "false";
  j += ",\"lux\":" + String(luxNow, 1);
  j += ",\"min\":" + String(luxMin, 0);
  j += ",\"max\":" + String(luxMax, 0);
  j += ",\"hold\":"; j += holdOn ? "true" : "false";
  j += ",\"rating\":\""; j += rating(luxNow); j += "\"}";
  server.send(200, "application/json", j);
}

void resetMinMax() { luxMin = luxNow; luxMax = luxNow; }

// ---------- Button: short press = hold, long press = reset ----------
void checkButton() {
  static bool lastState = HIGH;
  static unsigned long pressedAt = 0;
  bool s = digitalRead(BUTTON_PIN);
  if (s == LOW && lastState == HIGH) pressedAt = millis();          // pressed
  if (s == HIGH && lastState == LOW) {                              // released
    unsigned long t = millis() - pressedAt;
    if (t > 1000) resetMinMax();
    else if (t > 40) holdOn = !holdOn;                              // 40 ms debounce
  }
  lastState = s;
}

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Wire.begin(D2, D1);                       // SDA, SCL

  if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
    Serial.println(F("OLED not found - check wiring and address"));
  }
  display.clearDisplay(); display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0); display.print(F("Connecting Wi-Fi...")); display.display();

  sensorOk = bhBegin();
  Serial.println(sensorOk ? F("BH1750 ready") : F("BH1750 not found"));

  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(F("IP: ")); Serial.println(WiFi.localIP());
    MDNS.begin("luxmeter");                 // http://luxmeter.local
  } else {
    Serial.println(F("Wi-Fi not connected, OLED only"));
  }

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/hold", []() { holdOn = !holdOn; server.send(200, "text/plain", "ok"); });
  server.on("/reset", []() { resetMinMax(); server.send(200, "text/plain", "ok"); });
  server.begin();
}

void loop() {
  server.handleClient();
  MDNS.update();
  checkButton();

  if (millis() - lastRead >= 500) {         // 2 readings per second
    lastRead = millis();
    if (!holdOn) {
      float lx = bhReadLux();
      if (lx < 0) {
        sensorOk = bhBegin();               // try to wake the sensor again
      } else {
        sensorOk = true;
        luxNow = lx;
        if (firstReading) { resetMinMax(); firstReading = false; }
        if (luxNow < luxMin) luxMin = luxNow;
        if (luxNow > luxMax) luxMax = luxNow;
      }
    }
    drawScreen();
  }
}

Testing and Using the Meter

  • Open the Serial Monitor at 115200 baud. You should see BH1750 ready and the IP address.
  • Cover the sensor with your finger: the reading should drop to near 0 lx and show Dark. Shine a phone torch on it: it should jump to several thousand lux.
  • Open http://luxmeter.local (or the IP address) on a phone on the same Wi-Fi. The value updates every second.
  • Hold the sensor flat at desk height, facing up, to measure work-surface light. Keep your body and shadow away from it.
  • Press the button briefly to HOLD a reading, and hold it for more than 1 second to reset min/max before a new survey.

Troubleshooting

ProblemFix
OLED shows “BH1750 not found”Check SCL to D1 and SDA to D2 (they are easy to swap), 3V3 and GND. Check the ADDR pin: to GND for 0x23, or change BH1750_ADDR to 0x5C if it is tied high.
OLED stays blankMost 0.96 inch OLEDs use address 0x3C; some use 0x3D. Run an I2C scanner sketch and update OLED_ADDR. Check the VCC/GND order printed on the module.
Reading stuck at 0 or 546120 means the sensor is covered or in reset; 54612 (65535 / 1.2) is the top of the range in direct sunlight. Shade the sensor or move indoors.
Readings jump aroundFluorescent and cheap LED lamps flicker. Hold the meter still; for a smoother value, average several readings in the code.
Web page does not openCheck the IP on the OLED bottom line and keep the phone on the same 2.4 GHz Wi-Fi. Use the IP address if luxmeter.local does not work on Android.
“Wi-Fi offline” on the OLEDCheck the SSID and password (case-sensitive). The ESP8266 only supports 2.4 GHz networks.
Button does nothingThe button must connect D5 to GND. Use the two legs on opposite sides of a 4-leg tactile button.

Ideas to Extend

  • Add a relay on D6 and switch a lamp on automatically when the desk falls below 300 lx.
  • Log the readings every minute to a Google Sheet or an MQTT broker to see how daylight changes in a room.
  • Run it from a small Li-ion cell with a TP4056 charger board for a truly portable meter.

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.

Wemos D1 Mini Bidirectional Visitor Counter with IR Sensors, OLED, Auto Light & Wi-Fi Dashboard

Wemos D1 Mini bidirectional visitor counter with two IR obstacle sensors on a door frame, OLED showing people inside, relay module with lamp, buzzer, BC547 and reset button

Build a Wemos D1 Mini bidirectional visitor counter that uses two IR sensors to tell entries from exits, shows people inside on an OLED, switches the room light on while anyone is inside, beeps at full capacity and serves a live Wi-Fi dashboard.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts11 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

Shops, classrooms, libraries and small offices often want to know how many people are inside right now, not just how many walked past the door. A single sensor cannot tell the difference between someone coming in and someone going out. This Wemos D1 Mini visitor counter uses two IR sensors placed side by side on the door frame, so it knows the direction of every person and keeps an accurate count of entries, exits and people inside.

It combines several useful features in one build: a 0.96″ OLED shows the live count, a relay switches the room light on as soon as the first person enters and off when the last one leaves (an easy energy saver), a buzzer warns when the room reaches its maximum capacity, and a Wi-Fi dashboard on your phone shows everything and lets you change the limit or reset the counts. Counts are saved to flash, so a power cut does not lose them.

Wemos D1 Mini bidirectional visitor counter with two IR obstacle sensors on a door frame, OLED showing people inside, relay module with lamp, buzzer, BC547 and reset button

How It Works

  • Two beams, one direction: sensor A faces across the outer edge of the door and sensor B across the inner edge. A person walking in blocks A first and then B. A person walking out blocks B first and then A.
  • State machine: the code waits in IDLE. If A goes LOW first it moves to A_FIRST and counts an entry when B is also blocked within 1.5 seconds. If B goes LOW first it counts an exit when A follows. It then waits until both beams are clear before it looks for the next person, so one person is never counted twice.
  • People inside: inside = entries − exits. Exits are never allowed to exceed entries, so the number cannot go negative after a false trigger.
  • Auto light: the relay on D7 is ON whenever at least one person is inside and OFF when the room is empty.
  • Capacity alarm: when inside reaches the maximum (20 by default) the buzzer gives a double beep for every new entry and the OLED and web page show FULL.
  • Wi-Fi dashboard: the D1 Mini runs a web server at its IP address and at http://visitors.local. The page asks /data every 2 seconds for a small JSON reply and has buttons to set the maximum capacity and reset the counts.
  • Saving counts: entries, exits and the maximum are stored in the ESP8266 EEPROM area every 5 minutes when they change, which keeps flash wear low. Hold the reset button for 2 seconds to clear them.

Components Required

  • Wemos D1 Mini (ESP8266) – 1
  • FC-51 IR obstacle sensor module (3.3–5 V) – 2
  • 0.96″ SSD1306 I2C OLED display (128×64) – 1
  • 5V single-channel relay module (opto/transistor input, works with 3.3 V signal) – 1
  • Active 5V buzzer – 1
  • BC547 NPN transistor + 1 kΩ resistor – 1 each
  • Tactile push button (reset) – 1
  • 5V 2A USB power supply – 1
  • Breadboard or perfboard, jumper wires and 3-core cable for the sensors – 1 set
  • Small enclosure and double-sided tape for mounting the sensors on the door frame – 1
  • LED bulb/lamp with holder for the relay (or use the existing room light through the relay, with care) – 1

Wiring Table

Module pinWemos D1 Mini pinNotes
IR sensor A VCC / GND / OUT5V / GND / D5 (GPIO14)Outside edge of door; OUT is LOW when blocked
IR sensor B VCC / GND / OUT5V / GND / D6 (GPIO12)Inside edge of door, 8–12 cm from A
OLED VCC / GND5V / GNDUse 3V3 if your OLED has no regulator
OLED SDA / SCLD2 (GPIO4) / D1 (GPIO5)I2C address 0x3C
Relay module VCC / GND / IN5V / GND / D7 (GPIO13)Choose a module that triggers from a 3.3 V signal
Relay COM / NOLamp live wire (switched)Lamp is ON when relay is energised
BC547 baseD8 (GPIO15) through 1 kΩEmitter to GND
Buzzer + / –5V / BC547 collectorActive buzzer
Reset buttonD3 (GPIO0) and GNDInternal pull-up; don’t hold it while powering up

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.

Wemos D1 Mini Bidirectional Visitor Counter – Pin-Accurate Wiring WEMOS D1 MINI 5V 5V to IR A/B VCC, relay VCC, buzzer +, OLED VCC GND Common ground for every module D5 GPIO14 IR sensor A (outside) OUT D6 GPIO12 IR sensor B (inside) OUT D2 GPIO4 OLED SDA D1 GPIO5 OLED SCL D7 GPIO13 Relay module IN (HIGH = light ON) D8 GPIO15 1 kΩ to BC547 base, buzzer – to collector D3 GPIO0 Reset button to GND (hold 2 s) IR sensors: mount A on the outside edge and B on the inside edge of the door frame, 8–12 cm apart, about 90 cm high. BC547: emitter to GND, collector to buzzer –, buzzer + to 5V. OLED here runs from 5V (most modules have a 3.3 V regulator). Relay contacts (COM/NO) switch the lamp. Mains wiring must be enclosed and done by a qualified person.
Pin-accurate connection diagram for the Wemos D1 Mini bidirectional visitor counter.

Mounting the Sensors

  • Fix both IR modules on the same side of the door frame at about waist height (85–100 cm) so they see a body, not legs or a swinging bag.
  • Keep them 8–12 cm apart along the direction of walking. Too close and both trigger at the same moment; too far and a slow person times out.
  • Point them across the doorway and turn each blue trimmer until the module’s LED just lights when you stand in the doorway and goes off when it is empty. For doors wider than about 30 cm, use E18-D80NK sensors (up to 80 cm) instead of FC-51.
  • Avoid direct sunlight on the sensors; IR modules get confused by strong sunlight.

Code

Install the ESP8266 board package in the Arduino IDE and the Adafruit SSD1306 and Adafruit GFX libraries. Select LOLIN(WEMOS) D1 R2 & mini, put your Wi-Fi name and password in place of the placeholders and upload. The sketch compiles for the D1 Mini with the ESP8266 core 3.1.2.

/*
  Wemos D1 Mini Bidirectional Visitor Counter
  2x IR obstacle sensors + 0.96" SSD1306 OLED + auto light relay + buzzer + Wi-Fi dashboard
  Arduino Project Hub - ardiunoprojecthub.online

  Pins (Wemos D1 Mini):
    IR sensor A (outside of door) OUT -> D5 (GPIO14)   (LOW = beam blocked)
    IR sensor B (inside of door)  OUT -> D6 (GPIO12)   (LOW = beam blocked)
    OLED SDA / SCL                    -> D2 (GPIO4) / D1 (GPIO5)
    Relay module IN (room light)      -> D7 (GPIO13)   (HIGH = light ON)
    Buzzer driver                     -> D8 (GPIO15) -> 1k -> BC547 base
    Reset button                      -> D3 (GPIO0) to GND (do not hold it while powering up)
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

// ---------- Pins ----------
const uint8_t PIN_IR_A   = D5;   // outside sensor
const uint8_t PIN_IR_B   = D6;   // inside sensor
const uint8_t PIN_RELAY  = D7;   // room light relay
const uint8_t PIN_BUZZER = D8;   // buzzer transistor
const uint8_t PIN_RESET  = D3;   // reset counts button

// ---------- Settings ----------
const unsigned long PASS_TIMEOUT_MS = 1500;   // max time between sensor A and B for one person
const unsigned long SAVE_EVERY_MS   = 300000; // save counts to flash every 5 min if changed
int maxCapacity = 20;                         // buzzer warns when inside >= this (change from web)

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
ESP8266WebServer server(80);

struct Counts { uint32_t magic; long entries; long exits; int maxCap; };
long entries = 0, exitsCount = 0;
bool dirty = false;
unsigned long lastSave = 0;

// direction state machine
enum State { IDLE, A_FIRST, B_FIRST, WAIT_CLEAR };
State state = IDLE;
unsigned long stateTime = 0;

long inside() { long n = entries - exitsCount; return n < 0 ? 0 : n; }

bool blockedA() { return digitalRead(PIN_IR_A) == LOW; }
bool blockedB() { return digitalRead(PIN_IR_B) == LOW; }

void beep(int ms) { digitalWrite(PIN_BUZZER, HIGH); delay(ms); digitalWrite(PIN_BUZZER, LOW); }

void loadCounts() {
  Counts c; EEPROM.get(0, c);
  if (c.magic == 0xC0FFEE65) { entries = c.entries; exitsCount = c.exits; maxCapacity = c.maxCap; }
}
void saveCounts() {
  Counts c = { 0xC0FFEE65, entries, exitsCount, maxCapacity };
  EEPROM.put(0, c); EEPROM.commit(); dirty = false; lastSave = millis();
}
void resetCounts() { entries = 0; exitsCount = 0; saveCounts(); beep(80); }

void updateOutputs() {
  digitalWrite(PIN_RELAY, inside() > 0 ? HIGH : LOW);   // light on while anyone is inside
}

void drawOled() {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(1); oled.setCursor(0, 0); oled.print("INSIDE");
  oled.setCursor(80, 0); oled.print(inside() > 0 ? "LIGHT ON" : "LIGHT OFF");
  oled.setTextSize(3); oled.setCursor(0, 14); oled.print(inside());
  oled.setTextSize(1);
  oled.setCursor(0, 44); oled.print("IN:"); oled.print(entries);
  oled.setCursor(64, 44); oled.print("OUT:"); oled.print(exitsCount);
  oled.setCursor(0, 56);
  if (inside() >= maxCapacity) oled.print("FULL! max "); else oled.print("max ");
  oled.print(maxCapacity);
  if (WiFi.status() == WL_CONNECTED) { oled.setCursor(80, 56); oled.print("WiFi OK"); }
  oled.display();
}

void countEntry() {
  entries++; dirty = true; beep(40);
  if (inside() >= maxCapacity) { beep(150); delay(80); beep(150); }
}
void countExit() {
  if (exitsCount < entries) { exitsCount++; dirty = true; }
}

// Reads the two sensors and decides the direction of each person.
void handleSensors() {
  bool a = blockedA(), b = blockedB();
  unsigned long now = millis();
  switch (state) {
    case IDLE:
      if (a && !b) { state = A_FIRST; stateTime = now; }
      else if (b && !a) { state = B_FIRST; stateTime = now; }
      break;
    case A_FIRST:                       // outside first -> person coming in
      if (b) { countEntry(); state = WAIT_CLEAR; }
      else if (now - stateTime > PASS_TIMEOUT_MS) state = WAIT_CLEAR;
      break;
    case B_FIRST:                       // inside first -> person going out
      if (a) { countExit(); state = WAIT_CLEAR; }
      else if (now - stateTime > PASS_TIMEOUT_MS) state = WAIT_CLEAR;
      break;
    case WAIT_CLEAR:                    // wait until the doorway is empty again
      if (!a && !b) { state = IDLE; delay(50); }
      break;
  }
}

// ---------- Web dashboard ----------
const char PAGE[] PROGMEM = R"HTML(<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Visitor Counter</title><style>body{font-family:Arial;background:#0f172a;color:#e2e8f0;text-align:center;margin:0;padding:16px}
.big{font-size:72px;font-weight:bold;color:#38bdf8}.row{display:flex;gap:10px;justify-content:center}
.card{background:#1e293b;border-radius:12px;padding:12px 18px;min-width:90px}.full{color:#f87171}
button,input{font-size:16px;padding:8px 12px;border-radius:8px;border:0;margin:6px}</style></head><body>
<h2>Room Visitor Counter</h2><div class="card"><div>People inside</div><div class="big" id="in">-</div><div id="st"></div></div><br>
<div class="row"><div class="card">Entries<br><b id="e">-</b></div><div class="card">Exits<br><b id="x">-</b></div><div class="card">Light<br><b id="l">-</b></div></div>
<p>Max capacity: <input id="m" type="number" min="1" max="500" style="width:80px"><button onclick="setMax()">Save</button></p>
<button onclick="if(confirm('Reset all counts?'))fetch('/reset').then(load)">Reset counts</button>
<script>function load(){fetch('/data').then(r=>r.json()).then(d=>{in_.textContent=d.inside;e.textContent=d.entries;x.textContent=d.exits;
l.textContent=d.light?'ON':'OFF';if(document.activeElement!==m)m.value=d.max;st.textContent=d.inside>=d.max?'ROOM FULL':'';st.className=d.inside>=d.max?'full':'';})}
var in_=document.getElementById('in');function setMax(){fetch('/setmax?v='+m.value).then(load)}load();setInterval(load,2000);</script></body></html>)HTML";

void handleRoot() { server.send_P(200, "text/html", PAGE); }
void handleData() {
  String j = "{\"inside\":" + String(inside()) + ",\"entries\":" + String(entries) +
             ",\"exits\":" + String(exitsCount) + ",\"max\":" + String(maxCapacity) +
             ",\"light\":" + String(inside() > 0 ? "true" : "false") + "}";
  server.send(200, "application/json", j);
}
void handleReset() { resetCounts(); server.send(200, "text/plain", "OK"); }
void handleSetMax() {
  int v = server.arg("v").toInt();
  if (v >= 1 && v <= 500) { maxCapacity = v; saveCounts(); }
  server.send(200, "text/plain", "OK");
}

void setup() {
  Serial.begin(115200);
  pinMode(PIN_IR_A, INPUT_PULLUP);
  pinMode(PIN_IR_B, INPUT_PULLUP);
  pinMode(PIN_RESET, INPUT_PULLUP);
  pinMode(PIN_RELAY, OUTPUT);  digitalWrite(PIN_RELAY, LOW);
  pinMode(PIN_BUZZER, OUTPUT); digitalWrite(PIN_BUZZER, LOW);

  EEPROM.begin(64);
  loadCounts();

  Wire.begin(D2, D1);
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found at 0x3C");
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE); oled.setCursor(0, 0);
  oled.print("Connecting Wi-Fi..."); oled.display();

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  unsigned long t = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t < 15000) delay(250);
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Open http://"); Serial.println(WiFi.localIP());
    MDNS.begin("visitors");             // also http://visitors.local
  } else {
    Serial.println("Wi-Fi not connected - counter still works offline");
  }
  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/reset", handleReset);
  server.on("/setmax", handleSetMax);
  server.begin();
  updateOutputs();
  drawOled();
}

void loop() {
  handleSensors();
  server.handleClient();
  MDNS.update();

  if (digitalRead(PIN_RESET) == LOW) {          // long press 2 s = reset counts
    unsigned long t = millis();
    while (digitalRead(PIN_RESET) == LOW && millis() - t < 2000) delay(10);
    if (millis() - t >= 2000) resetCounts();
  }

  static unsigned long lastDraw = 0;
  if (millis() - lastDraw > 250) { updateOutputs(); drawOled(); lastDraw = millis(); }
  if (dirty && millis() - lastSave > SAVE_EVERY_MS) saveCounts();
}

Testing

  • Open the Serial Monitor at 115200 baud and note the IP address after “Open http://”.
  • Walk in slowly through the door: IN should rise by one, INSIDE should show 1, the relay should click and the lamp should turn on.
  • Walk out: OUT rises, INSIDE returns to 0 and the lamp turns off.
  • Set the maximum to 2 on the web page, walk in twice and check the double beep and the FULL message.
  • Hold the reset button for 2 seconds and check that all counts go to zero.

Troubleshooting

ProblemFix
Entries counted as exitsSensors A and B are swapped. Swap the D5 and D6 wires or swap the pin numbers in the code.
One person counted twiceMove the sensors a little further apart or increase the 50 ms delay in WAIT_CLEAR. Make sure both module LEDs go off when the doorway is empty.
Nothing counted when walking fastReduce the gap between the sensors or raise PASS_TIMEOUT_MS only if people walk very slowly; fast walking needs a smaller gap, not a longer timeout.
Relay does not switchSome relay modules need a 5 V signal. Use a module with an optocoupler or transistor input, or drive IN through a BC547 like the buzzer.
Board will not boot or uploadD3 (GPIO0) and D8 (GPIO15) are boot pins. Do not hold the reset button at power-up and keep the 1 kΩ base resistor on D8.
Web page does not openCheck the IP address in the Serial Monitor, keep the phone on the same Wi-Fi, and try the IP if visitors.local does not work on Android.
OLED stays blankCheck SDA on D2 and SCL on D1, and try address 0x3D if 0x3C is not found.

Ideas to Extend

  • Log hourly entries to Google Sheets or ThingSpeak for footfall reports.
  • Add a DS3231 RTC to reset the counts automatically at midnight.
  • Add a second relay for a fan, or a green/red LED at the door showing whether the room is full.

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.

Wemos D1 Mini Wi-Fi Water Tank Level Monitor with JSN-SR04T & OLED

Wemos D1 Mini water tank level monitor with JSN-SR04T waterproof ultrasonic sensor on a tank lid, OLED display, buzzer and a phone showing the level gauge web page

Build a Wi-Fi water tank level monitor with a Wemos D1 Mini and a waterproof JSN-SR04T sensor that shows the level on an OLED and a phone web page and beeps when the tank is low or full.

  • DifficultyIntermediate
  • Build time2–4 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts10 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This Wemos D1 Mini water tank level monitor tells you how much water is in your overhead tank without climbing up to check. A waterproof JSN-SR04T ultrasonic sensor sits in the tank lid and measures the distance down to the water. The D1 Mini turns that into a percentage and litres, shows it on a small OLED display, serves a live tank gauge to any phone on your Wi-Fi, and beeps when the tank is nearly empty or about to overflow.

It is a practical intermediate project for homes, hostels and shops in India where rooftop tanks are filled by a motor. Because nothing touches the water except a sealed sensor head, there are no probes to rust, and the same build works for a 500 litre or a 2000 litre tank after you enter its depth.

Wemos D1 Mini water tank level monitor with JSN-SR04T waterproof ultrasonic sensor on a tank lid, OLED display, buzzer and a phone showing the level gauge web page

How It Works

  • Measuring the water: every 2 seconds the D1 Mini sends a 20 µs pulse on TRIG. The JSN-SR04T fires an ultrasonic ping and holds ECHO high until the echo comes back from the water surface. The pulse width divided by 58 gives the distance in centimetres. The sketch takes five readings and uses the middle one, which ignores ripples and stray echoes.
  • Distance to level: you enter two numbers: the distance from the sensor to the water when the tank is full, and the distance to the tank floor. The code maps the measured distance between those two points to 0 to 100 percent and then to litres using the tank capacity.
  • Blind zone: the JSN-SR04T cannot see anything closer than about 25 cm. Mount the sensor so the full water line stays at least 25 cm below its face, for example on a short pipe above the lid.
  • Level shifting: the sensor runs on 5V and its ECHO output is 5V. The D1 Mini pins are 3.3V only, so a 1 kΩ and 2 kΩ divider drops the echo signal to about 3.3V. TRIG works directly from the 3.3V pin.
  • Display and web page: the OLED shows the percentage in large digits, the litres, and a filling bar. The D1 Mini also runs a small web server at its IP address or http://watertank.local. The page draws a tank that fills up and asks /data every 3 seconds for fresh numbers.
  • Alarm: below 15 percent the buzzer gives a slow beep, and above 95 percent it beeps fast so you can switch off the pump. The button or the Mute button on the web page silences it, and the alarm turns itself back on the next time the level state changes.

Components Required

  • Wemos D1 Mini (ESP8266) – 1
  • JSN-SR04T (or AJ-SR04M) waterproof ultrasonic sensor with 2.5 m cable – 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
  • 1 kΩ resistor and 2 kΩ resistor (echo voltage divider) – 1 each
  • Push button (alarm mute) – 1
  • 5V 1A USB power adapter and long USB cable – 1
  • Small waterproof enclosure, cable glands and PVC pipe cap for the sensor – 1 set
  • Perfboard or breadboard and jumper wires – 1 set

Wiring Table

Part / pinWemos D1 Mini pinNotes
JSN-SR04T 5V / GND5V / GNDSensor board needs 5V
JSN-SR04T TRIGD5 (GPIO14)3.3V trigger is enough
JSN-SR04T ECHOD6 (GPIO12) through 1 kΩ, 2 kΩ from D6 to GNDNever connect ECHO directly
OLED VCC / GND3V3 / GND
OLED SDA / SCLD2 (GPIO4) / D1 (GPIO5)I2C address 0x3C
BC547 baseD8 (GPIO15) through 1 kΩD8 has a pull-down, so the buzzer stays quiet at boot
BC547 emitter / collectorGND / buzzer –Buzzer + goes to 5V
Mute buttonD7 (GPIO13) and GNDUses the internal pull-up

Connection Diagram

The illustration at the top shows how the parts are arranged. It is a layout guide only, and the pin labels in it are not exact. Follow the pin-accurate drawing below, which matches the wiring table.

Wemos D1 Mini Water Tank Level Monitor – Pin-Accurate Wiring 5V USB power D1 Mini 5V pin to JSN-SR04T 5V and buzzer + D1 Mini 3V3 to OLED VCC All GND pins joined together JSN-SR04T TRIG to D5 (GPIO14) ECHO to 1 kΩ to D6 (GPIO12) 2 kΩ from D6 to GND (5V echo becomes 3.3V) OLED (I2C) SDA to D2 (GPIO4) SCL to D1 (GPIO5) Address 0x3C Buzzer driver D8 (GPIO15) to 1 kΩ to BC547 base BC547 emitter to GND, collector to buzzer – Buzzer + to 5V Mute button One leg to D7 (GPIO13), other leg to GND (internal pull-up)
Pin-accurate connection diagram for the Wemos D1 Mini water tank level monitor.

Mounting on the Tank

  • Drill a hole in the tank lid that fits the JSN-SR04T head, or fix the head in a PVC end cap glued to a short pipe so it points straight down at the water.
  • Keep the sensor away from the inlet pipe and the tank walls so falling water and the walls do not cause false echoes.
  • Measure from the sensor face to the overflow level and to the tank floor with a tape, and put those numbers in SENSOR_TO_FULL_CM and SENSOR_TO_EMPTY_CM.
  • Put the D1 Mini, OLED and buzzer in a waterproof box near the tank or run the sensor cable down to a box inside the house. The JSN-SR04T cable can be extended to about 5 m with shielded wire.

Code

Install the esp8266 by ESP8266 Community board package in the Arduino IDE and select LOLIN(WEMOS) D1 R2 & mini. From the Library Manager install Adafruit SSD1306 and Adafruit GFX Library. Replace the Wi-Fi placeholders with your own network name and password, set the tank distances and capacity, then upload.

/*
  Wemos D1 Mini Wi-Fi Water Tank Level Monitor
  JSN-SR04T waterproof ultrasonic sensor + 0.96" SSD1306 OLED + buzzer alarm + web gauge
  Arduino Project Hub - ardiunoprojecthub.online

  Pins (Wemos D1 Mini):
    JSN-SR04T TRIG  -> D5 (GPIO14)
    JSN-SR04T ECHO  -> 1k -> D6 (GPIO12), 2k from D6 to GND (5V echo -> 3.3V)
    OLED SDA / SCL  -> D2 (GPIO4) / D1 (GPIO5)
    Buzzer driver   -> D8 (GPIO15) -> 1k -> BC547 base (buzzer on collector)
    Mute button     -> D7 (GPIO13) to GND (internal pull-up)
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

// ---------- Pins ----------
const uint8_t PIN_TRIG = D5;
const uint8_t PIN_ECHO = D6;
const uint8_t PIN_BUZZ = D8;
const uint8_t PIN_MUTE = D7;

// ---------- Tank settings (measure your own tank) ----------
const float SENSOR_TO_FULL_CM  = 25.0;   // distance from sensor face to water when the tank is FULL (>= 25 cm, the JSN-SR04T blind zone)
const float SENSOR_TO_EMPTY_CM = 125.0;  // distance from sensor face to the tank floor (EMPTY)
const float TANK_LITRES        = 1000.0; // total capacity, used to show litres
const int   LOW_ALARM_PCT      = 15;     // beep when the level falls below this
const int   HIGH_ALARM_PCT     = 95;     // beep when the tank is almost overflowing

Adafruit_SSD1306 oled(128, 64, &Wire, -1);
ESP8266WebServer server(80);

float lastDistance = -1;   // cm, -1 = no echo
int   levelPct = 0;
bool  muted = false;
int   lastAlarmState = 0;  // 0 none, 1 low, 2 high
unsigned long lastRead = 0, lastBeep = 0;

// One distance reading in cm, or -1 if no echo
float readOnce() {
  digitalWrite(PIN_TRIG, LOW);
  delayMicroseconds(5);
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(20);             // JSN-SR04T likes a longer trigger pulse
  digitalWrite(PIN_TRIG, LOW);
  unsigned long us = pulseIn(PIN_ECHO, HIGH, 30000UL); // ~5 m max
  if (us == 0) return -1;
  return us * 0.0343f / 2.0f;
}

// Median of 5 readings to ignore stray echoes from ripples
float readDistance() {
  float v[5]; int n = 0;
  for (int i = 0; i < 5; i++) {
    float d = readOnce();
    if (d > 0) v[n++] = d;
    delay(60);
  }
  if (n == 0) return -1;
  for (int i = 0; i < n - 1; i++)
    for (int j = i + 1; j < n; j++)
      if (v[j] < v[i]) { float t = v[i]; v[i] = v[j]; v[j] = t; }
  return v[n / 2];
}

int distanceToPercent(float d) {
  float span = SENSOR_TO_EMPTY_CM - SENSOR_TO_FULL_CM;
  float pct = (SENSOR_TO_EMPTY_CM - d) * 100.0f / span;
  if (pct < 0) pct = 0;
  if (pct > 100) pct = 100;
  return (int)(pct + 0.5f);
}

void drawOled() {
  oled.clearDisplay();
  oled.setTextColor(SSD1306_WHITE);
  oled.setTextSize(1);
  oled.setCursor(0, 0);
  oled.print("WATER TANK");
  oled.setCursor(80, 0);
  oled.print(muted ? "MUTED" : WiFi.isConnected() ? "WiFi" : "noWiFi");

  if (lastDistance < 0) {
    oled.setTextSize(2);
    oled.setCursor(0, 24);
    oled.print("NO ECHO");
  } else {
    oled.setTextSize(3);
    oled.setCursor(0, 16);
    oled.print(levelPct);
    oled.print("%");
    oled.setTextSize(1);
    oled.setCursor(0, 46);
    oled.print((int)(TANK_LITRES * levelPct / 100));
    oled.print(" L");
    if (levelPct <= LOW_ALARM_PCT) oled.print("  LOW!");
    if (levelPct >= HIGH_ALARM_PCT) oled.print("  FULL!");
  }
  // vertical tank bar on the right
  oled.drawRect(104, 12, 22, 50, SSD1306_WHITE);
  int h = (lastDistance < 0) ? 0 : 46 * levelPct / 100;
  oled.fillRect(106, 60 - h, 18, h, SSD1306_WHITE);
  oled.display();
}

void handleRoot() {
  String ip = WiFi.localIP().toString();
  String page =
    "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>"
    "<title>Water Tank</title><style>body{font-family:Arial;text-align:center;background:#eef4fb;margin:0;padding:20px}"
    ".tank{width:140px;height:260px;border:4px solid #1565c0;border-radius:10px;margin:20px auto;position:relative;background:#fff;overflow:hidden}"
    "#w{position:absolute;bottom:0;width:100%;background:#42a5f5;transition:height 1s}"
    "#p{font-size:42px;font-weight:bold}button{padding:10px 18px;font-size:16px;border:0;border-radius:6px;background:#1565c0;color:#fff}</style></head>"
    "<body><h2>Water Tank Level</h2><div class='tank'><div id='w' style='height:0'></div></div>"
    "<div id='p'>--%</div><div id='l'></div><p id='s'></p><button onclick=\"fetch('/mute')\">Mute / Unmute alarm</button>"
    "<script>function u(){fetch('/data').then(r=>r.json()).then(d=>{"
    "document.getElementById('w').style.height=d.pct+'%';"
    "document.getElementById('p').textContent=d.ok?d.pct+'%':'No echo';"
    "document.getElementById('l').textContent=d.litres+' litres, '+d.cm+' cm to water';"
    "document.getElementById('w').style.background=d.pct<=" + String(LOW_ALARM_PCT) + "?'#e53935':'#42a5f5';"
    "document.getElementById('s').textContent=(d.muted?'Alarm muted':'Alarm on');})}"
    "setInterval(u,3000);u();</script></body></html>";
  server.send(200, "text/html", page);
}

void handleData() {
  String j = "{\"ok\":" + String(lastDistance > 0 ? "true" : "false") +
             ",\"pct\":" + String(levelPct) +
             ",\"litres\":" + String((int)(TANK_LITRES * levelPct / 100)) +
             ",\"cm\":" + String(lastDistance, 1) +
             ",\"muted\":" + String(muted ? "true" : "false") + "}";
  server.send(200, "application/json", j);
}

void handleMute() {
  muted = !muted;
  server.send(200, "text/plain", muted ? "muted" : "alarm on");
}

void setup() {
  Serial.begin(115200);
  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);
  pinMode(PIN_BUZZ, OUTPUT);
  digitalWrite(PIN_BUZZ, LOW);
  pinMode(PIN_MUTE, INPUT_PULLUP);

  Wire.begin(D2, D1);
  if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found at 0x3C");
  oled.clearDisplay(); oled.setTextColor(SSD1306_WHITE);
  oled.setCursor(0, 0); oled.print("Connecting Wi-Fi..."); oled.display();

  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.isConnected()) {
    Serial.print("Open http://"); Serial.println(WiFi.localIP());
    MDNS.begin("watertank");   // http://watertank.local
  } else {
    Serial.println("Wi-Fi not connected, running offline (OLED + buzzer still work)");
  }
  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/mute", handleMute);
  server.begin();
}

void loop() {
  server.handleClient();
  MDNS.update();

  // Mute button (simple debounce)
  static bool lastBtn = HIGH;
  bool btn = digitalRead(PIN_MUTE);
  if (lastBtn == HIGH && btn == LOW) { muted = !muted; delay(30); }
  lastBtn = btn;

  if (millis() - lastRead > 2000) {
    lastRead = millis();
    lastDistance = readDistance();
    if (lastDistance > 0) levelPct = distanceToPercent(lastDistance);
    Serial.printf("Distance %.1f cm, level %d %%\n", lastDistance, levelPct);

    int state = 0;
    if (lastDistance > 0 && levelPct <= LOW_ALARM_PCT) state = 1;
    if (lastDistance > 0 && levelPct >= HIGH_ALARM_PCT) state = 2;
    if (state != lastAlarmState) { muted = false; lastAlarmState = state; } // un-mute when the alarm changes
    drawOled();
  }

  // Alarm: short beeps for LOW, fast beeps for FULL
  if (lastAlarmState != 0 && !muted) {
    unsigned long period = (lastAlarmState == 2) ? 400 : 1500;
    if (millis() - lastBeep > period) {
      lastBeep = millis();
      digitalWrite(PIN_BUZZ, HIGH); delay(120); digitalWrite(PIN_BUZZ, LOW);
    }
  }
}

Testing

  • Open the Serial Monitor at 115200 baud and note the IP address after “Open http://”.
  • Before fitting the sensor on the tank, point it at a wall 50 cm and 100 cm away and check that the distance readings are close.
  • Mount it on the tank and compare the percentage with the real water level you see.
  • Let the level drop below 15 percent (or temporarily raise LOW_ALARM_PCT) and check the slow beep, then press the button to mute it.
  • Open the web page on your phone and make sure the tank picture follows the OLED.

Troubleshooting

ProblemFix
OLED or web page shows No echoCheck the 5V supply to the sensor and the ECHO divider. Make sure the sensor head points straight down and is not touching anything.
Readings stuck near 20 to 25 cmThe water is inside the blind zone. Raise the sensor on a pipe so the full level is at least 25 cm below it.
Level jumps while the pump runsFalling water and splashes reflect the sound. Move the sensor away from the inlet or ignore readings while filling.
D1 Mini does not boot with the buzzer circuitUse D8 only through the 1 kΩ resistor to the transistor base. Do not add a pull-up on D8, as it must be low at boot.
Web page does not openThe phone must be on the same 2.4 GHz Wi-Fi. Use the IP address if watertank.local does not work on Android.
Wrong percentageRe-measure the full and empty distances from the sensor face, not from the lid.

Ideas to Extend

  • Add a relay module to switch the pump on at 20 percent and off at 95 percent for a fully automatic tank.
  • Send a phone notification with ntfy when the tank is low.
  • Log daily water use by recording the level every hour.

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.

Wemos D1 Mini Wi-Fi Servo Controller with Web Slider

Wemos D1 Mini wired to an SG90 servo on a breadboard, with a phone showing the web slider control page

Control an SG90 servo from your phone with a Wemos D1 Mini: a built-in web page with a 0 to 180 degree slider and preset buttons, no app needed.

  • DifficultyEasy
  • Build time1–2 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts5 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This Wemos D1 Mini Wi-Fi servo controller lets you move a small SG90 servo from any phone or laptop on your home Wi-Fi. The D1 Mini hosts its own web page with a big angle readout, a 0 to 180 degree slider and three preset buttons, so there is no app to install and no cloud account to set up.

It is a quick, beginner-friendly ESP8266 project with only three wires. Once it works, the same idea can open a pet feeder flap, point a camera, press a light switch, or move a pointer on a dashboard.

Wemos D1 Mini wired to an SG90 servo on a breadboard, with a phone showing the web slider control page

How It Works

  • Wi-Fi and web server: the D1 Mini joins your Wi-Fi in station mode and starts a web server on port 80. The Serial Monitor prints its IP address, and it also answers at http://d1servo.local on devices that support mDNS.
  • The web page: the page is stored in flash memory. When you drag the slider, a little JavaScript sends /set?angle=NN to the board. It waits 60 ms between requests so a fast drag does not flood the ESP8266.
  • Servo signal: the Servo library sends a 50 Hz pulse on D5 (GPIO14). A 500 µs pulse means 0 degrees and a 2400 µs pulse means 180 degrees, which matches most SG90 servos.
  • Real position on reload: when the page opens it asks /angle for the current angle, so the slider always shows where the servo actually is, even if someone else moved it from another phone.
  • Status LED: the on-board LED blinks while the board connects and stays on once it is on Wi-Fi.

Components Required

  • Wemos D1 Mini (ESP8266) – 1
  • SG90 micro servo motor (or MG90S) – 1
  • 470 µF 10V electrolytic capacitor (across servo 5V and GND) – 1
  • Breadboard and male-to-male jumper wires
  • Micro-USB cable and 5V 1A USB charger or power bank – 1

Wiring Table

Servo wireWemos D1 Mini pinNotes
Orange (signal)D5 (GPIO14)PWM output from the Servo library
Red (VCC)5VComes straight from USB; use a 1A or better supply
Brown (GND)GCommon ground
470 µF capacitorAcross 5V and G near the servoLong leg (+) to 5V; stops resets when the servo starts
On-board LEDGPIO2No wiring needed

Connection Diagram

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

Wemos D1 Mini Wi-Fi Servo Controller – Pin-Accurate Wiring Power Micro-USB 5V into the D1 Mini D1 Mini 5V pin: servo red wire D1 Mini G pin: servo brown wire 470 µF capacitor across servo 5V and GND (+ to 5V) SG90 servo Orange (signal) wire to D5 (GPIO14) Red (VCC) wire to 5V Brown (GND) wire to G Status LED On-board LED (GPIO2): blinks while connecting, solid when on Wi-Fi
Pin-accurate connection diagram for the Wemos D1 Mini Wi-Fi servo controller.

Code

Install the ESP8266 board package in the Arduino IDE (Boards Manager, search “esp8266”) and choose LOLIN(WEMOS) D1 R2 & mini. The Servo, web server and mDNS libraries come with the board package, so nothing else is needed. Put your own Wi-Fi name and password in place of the placeholders before uploading.

/*
  Wemos D1 Mini Wi-Fi Servo Controller with Web Slider
  Arduino Project Hub - https://ardiunoprojecthub.online

  Open the D1 Mini's IP address in a phone or laptop browser on the same Wi-Fi.
  Drag the slider (0-180 degrees) or tap a preset button to move an SG90 servo.

  Wiring: servo signal (orange) -> D5 (GPIO14)
          servo VCC (red)       -> 5V
          servo GND (brown)     -> G
  Board: LOLIN(WEMOS) D1 R2 & mini (ESP8266 core)
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Servo.h>

const char* WIFI_SSID = "YOUR_WIFI_NAME";      // <-- your Wi-Fi name
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";  // <-- your Wi-Fi password

const uint8_t SERVO_PIN = D5;    // GPIO14
const int MIN_US = 500;          // pulse width for 0 degrees (SG90)
const int MAX_US = 2400;         // pulse width for 180 degrees (SG90)

ESP8266WebServer server(80);
Servo servo;
int angle = 90;                  // current angle, starts in the middle

// The web page is stored in flash (PROGMEM) to save RAM
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>D1 Mini Servo</title>
<style>
body{font-family:Arial,sans-serif;text-align:center;background:#f4f6f8;margin:0;padding:20px}
.card{background:#fff;max-width:360px;margin:auto;padding:20px;border-radius:12px;box-shadow:0 2px 8px #0002}
h2{margin-top:0}#a{font-size:48px;font-weight:bold;color:#00979d}
input[type=range]{width:100%;height:30px}
button{margin:6px;padding:10px 16px;font-size:16px;border:0;border-radius:8px;background:#00979d;color:#fff}
</style></head><body><div class="card">
<h2>Servo Controller</h2><div id="a">--</div><div>degrees</div>
<input type="range" id="s" min="0" max="180" value="90">
<div><button onclick="go(0)">0&deg;</button><button onclick="go(90)">90&deg;</button><button onclick="go(180)">180&deg;</button></div>
</div><script>
var s=document.getElementById('s'),a=document.getElementById('a'),t;
function go(v){s.value=v;a.textContent=v;fetch('/set?angle='+v);}
s.oninput=function(){a.textContent=s.value;clearTimeout(t);t=setTimeout(function(){fetch('/set?angle='+s.value);},60);};
fetch('/angle').then(r=>r.text()).then(v=>{s.value=v;a.textContent=v;});
</script></body></html>
)HTML";

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

// /set?angle=0..180 moves the servo
void handleSet() {
  if (!server.hasArg("angle")) {
    server.send(400, "text/plain", "missing angle");
    return;
  }
  angle = constrain(server.arg("angle").toInt(), 0, 180);
  servo.write(angle);
  Serial.printf("Servo -> %d deg\n", angle);
  server.send(200, "text/plain", String(angle));
}

// /angle returns the current angle so the page shows the real position
void handleAngle() {
  server.send(200, "text/plain", String(angle));
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);          // on-board LED is active LOW (off)

  servo.attach(SERVO_PIN, MIN_US, MAX_US);
  servo.write(angle);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));  // blink while connecting
    delay(250);
    Serial.print('.');
  }
  digitalWrite(LED_BUILTIN, LOW);           // solid on = connected
  Serial.print("\nOpen http://");
  Serial.println(WiFi.localIP());

  if (MDNS.begin("d1servo")) {
    Serial.println("or http://d1servo.local");
  }

  server.on("/", handleRoot);
  server.on("/set", handleSet);
  server.on("/angle", handleAngle);
  server.begin();
}

void loop() {
  server.handleClient();
  MDNS.update();
}

Testing

  • Upload the sketch and open the Serial Monitor at 115200 baud. Wait for the line “Open http://192.168.x.x”.
  • Type that address into a phone browser on the same Wi-Fi. The page should show 90 and the servo should sit in the middle.
  • Tap 0 and 180 and check that the horn swings fully both ways without buzzing at the ends.
  • Drag the slider slowly: the servo should follow smoothly and the Serial Monitor should print each new angle.

Troubleshooting

ProblemFix
Board keeps resetting when the servo movesThe servo draws a current spike. Add the 470 µF capacitor across 5V and G, use a better USB cable, and a 1A or higher charger.
Serial Monitor shows dots foreverCheck the Wi-Fi name and password. The ESP8266 works only on 2.4 GHz Wi-Fi, not 5 GHz.
Page does not openMake sure the phone is on the same Wi-Fi, not mobile data. Use the IP address if d1servo.local does not work (many Android phones do not support .local).
Servo buzzes or strains at 0 or 180 degreesYour servo has a smaller range. Change MIN_US to 600 and MAX_US to 2300, or limit the slider in the page.
Servo jitters at restKeep the signal wire short and away from the power wires, and make sure the servo ground and the D1 Mini ground are the same pin.

Ideas to Extend

  • Save the last angle in EEPROM so the servo returns to it after a power cut.
  • Add a second servo on D6 for a pan and tilt camera mount.
  • Add a schedule with NTP time to open a pet feeder flap at fixed times.

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.

Wemos D1 Mini Smart Garage Door Controller with Reed Switches, Ultrasonic Car Sensor & Web App

Wemos D1 Mini smart garage door controller with relay shield, two reed switches, HC-SR04 ultrasonic sensor, buzzer and opener push button

Build a Wemos D1 Mini smart garage door controller with a relay shield, two reed switches, an HC-SR04 car sensor, warning buzzer, auto-close and a PIN-protected web app. Wiring table, diagram and full code.

  • DifficultyAdvanced
  • Build time5–8 hours
  • Board / MCUWemos D1 Mini (ESP8266)
  • Parts9 items
  • CodeArduino C++

Need it ready-made? Buy Ready Project

This Wemos D1 Mini smart garage door controller lets you open and close your existing garage door from your phone, see whether the door is closed, open or moving, and check if the car is parked inside. It also beeps a warning before every remote close and can close the door on its own if someone forgets it open. Everything runs on the cheap ESP8266-based Wemos D1 Mini, with a relay shield, two magnetic reed switches, an HC-SR04 ultrasonic sensor and a buzzer.

It is a big combination build: Wi-Fi web server, relay control, position sensing, distance measurement and a safety timer all in one sketch. It works with almost any sectional or roller garage door opener that has a wall push button, because the relay simply “presses” that button for half a second. It does not touch the opener’s mains wiring.

Wemos D1 Mini smart garage door controller with relay shield, two reed switches, HC-SR04 ultrasonic sensor, buzzer and opener push button

How It Works

  • Opener control: most openers start, stop or reverse the motor when their two push-button wires are shorted. The relay contacts (COM and NO) are wired in parallel with that button, and the code closes them for 500 ms each time you tap the button on the web page.
  • Door position: one reed switch is fixed where the door rests when fully closed and another where it rests when fully open. A magnet on the door closes each switch, pulling D5 or D6 LOW. Neither switch active means the door is moving or stopped half way.
  • Car detection: the HC-SR04 is mounted on the ceiling, facing down. Once a second the code measures the distance. A reading under 80 cm (adjustable) means the roof or bonnet of a car is under the sensor.
  • Safety warning: before every remote close and every auto-close, the active buzzer beeps for about 3 seconds so anyone under the door has time to move. Your opener’s own photo-eye safety sensors keep working as normal.
  • Auto-close: if the door stays fully open for more than 10 minutes (set by AUTO_CLOSE_MIN), the controller warns and closes it.
  • Web app: the D1 Mini serves a phone-friendly page at its IP address or at http://garage.local. The page refreshes the status every 2 seconds, and the Open/Close button only works with the correct PIN.

Components Required

  • Wemos D1 Mini (ESP8266) – 1
  • Wemos D1 Mini relay shield (relay on D1) – 1, or a 3.3V-compatible 1-channel relay module
  • Magnetic reed switches (door/window contact type, normally open) – 2
  • HC-SR04 ultrasonic distance sensor – 1
  • Active buzzer (3.3V–5V) – 1
  • Resistors: 1k – 1, 2k (or 2.2k) – 1, for the ECHO voltage divider
  • 5V 2 A USB adapter and USB cable
  • Two-core cable (bell wire) to the opener’s push-button terminals and to the reed switches
  • Mini breadboard or small perfboard, jumper wires and a plastic enclosure

Wiring Table

Part / pinWemos D1 Mini pinNotes
Relay shield signalD1 (GPIO5)Stack the shield, or wire IN of a relay module to D1
Relay COM and NOOpener push-button terminalsIn parallel with the existing wall button; polarity does not matter
Reed switch (closed position)D5 (GPIO14) and GNDInternal pull-up; LOW when the door is closed
Reed switch (open position)D6 (GPIO12) and GNDLOW when the door is fully open
HC-SR04 VCC5V
HC-SR04 GNDG (GND)
HC-SR04 TRIGD7 (GPIO13)3.3V trigger works fine
HC-SR04 ECHOD8 (GPIO15) through 1k2k from D8 to GND drops the 5V echo to about 3.3V
Active buzzer (+)D2 (GPIO4)
Active buzzer (-)G (GND)
5V USB adapterUSB socketPowers the board, relay and sensor

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.

Wemos D1 Mini Smart Garage Door Controller – Pin-Accurate Wiring Power 5V USB adapter (2 A) to the Wemos D1 Mini USB socket D1 Mini 5V pin: relay shield 5V (stacked) and HC-SR04 VCC D1 Mini G (GND): relay shield, HC-SR04 GND, buzzer (-), both reed switches Relay shield Relay shield stacked on the D1 Mini, signal on D1 (GPIO5) Relay COM and NO in parallel with the opener’s wall push-button terminals Reed switches Closed-position reed switch: D5 (GPIO14) and GND Fully-open reed switch: D6 (GPIO12) and GND Internal pull-ups enabled in code, magnets fixed on the door HC-SR04 TRIG to D7 (GPIO13) ECHO through 1k to D8 (GPIO15); 2k from D8 to GND Mount on the ceiling above the car bonnet, facing down Buzzer Active 3.3V buzzer (+) to D2 (GPIO4), (-) to GND
Pin-accurate connection diagram for the Wemos D1 Mini smart garage door controller.

Code

Install the ESP8266 board package in the Arduino IDE (Boards Manager, search “esp8266”) and choose LOLIN(WEMOS) D1 R2 & mini. No extra libraries are needed. Replace the Wi-Fi placeholders and change the PIN before uploading. Open the Serial Monitor at 115200 baud to see the IP address, then open it (or http://garage.local) in your phone’s browser.

/*
  Wemos D1 Mini Smart Garage Door Controller
  - Relay shield pulses the opener's push-button input (open / stop / close)
  - Two reed switches report the closed and fully open positions
  - HC-SR04 ultrasonic sensor detects whether a car is parked inside
  - Active buzzer warns before every remote close and before auto-close
  - Web page (phone friendly) with live status and a PIN-protected button
  - Auto-close if the door stays open longer than AUTO_CLOSE_MIN minutes

  Board: LOLIN(WEMOS) D1 R2 & mini  (ESP8266 core, no extra libraries)
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

// ---------- User settings (placeholders) ----------
const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* DOOR_PIN  = "1234";        // change this PIN before use
const unsigned long AUTO_CLOSE_MIN = 10; // 0 = auto-close disabled
const int CAR_DISTANCE_CM = 80;        // closer than this = car present

// ---------- Pins ----------
const uint8_t RELAY_PIN  = D1;  // GPIO5  - relay shield (active HIGH)
const uint8_t BUZZER_PIN = D2;  // GPIO4  - active buzzer (+)
const uint8_t REED_CLOSED = D5; // GPIO14 - reed switch at closed position
const uint8_t REED_OPEN   = D6; // GPIO12 - reed switch at fully open position
const uint8_t TRIG_PIN   = D7;  // GPIO13 - HC-SR04 TRIG
const uint8_t ECHO_PIN   = D8;  // GPIO15 - HC-SR04 ECHO (through 1k/2k divider)

ESP8266WebServer server(80);

enum DoorState { DOOR_CLOSED, DOOR_OPEN, DOOR_MOVING };
unsigned long openSince = 0;     // when the door left the closed position
int carDistance = -1;            // last ultrasonic reading in cm
unsigned long lastSonar = 0;

DoorState readDoor() {
  bool closed = digitalRead(REED_CLOSED) == LOW;  // magnet near = LOW
  bool open   = digitalRead(REED_OPEN) == LOW;
  if (closed) return DOOR_CLOSED;
  if (open)   return DOOR_OPEN;
  return DOOR_MOVING;
}

const char* doorText(DoorState s) {
  return s == DOOR_CLOSED ? "Closed" : (s == DOOR_OPEN ? "Open" : "Moving / part open");
}

int readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000UL); // 30 ms timeout (~5 m)
  if (us == 0) return -1;                                // no echo
  return us / 58;                                        // microseconds to cm
}

// Beep a warning, then press the opener button for 500 ms
void pulseOpener(bool warnFirst) {
  if (warnFirst) {
    for (int i = 0; i < 6; i++) {          // about 3 seconds of beeps
      digitalWrite(BUZZER_PIN, HIGH); delay(250);
      digitalWrite(BUZZER_PIN, LOW);  delay(250);
    }
  }
  digitalWrite(RELAY_PIN, HIGH);
  delay(500);
  digitalWrite(RELAY_PIN, LOW);
}

void handleRoot() {
  String html = F("<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>"
    "<title>Garage Door</title><style>body{font-family:Arial;text-align:center;background:#f2f4f7;margin:0;padding:20px}"
    ".card{background:#fff;border-radius:14px;padding:20px;max-width:360px;margin:auto;box-shadow:0 2px 8px #0002}"
    "h1{font-size:22px}.s{font-size:28px;font-weight:bold;margin:10px}input{font-size:18px;padding:8px;width:120px;text-align:center}"
    "button{font-size:20px;padding:14px 30px;margin-top:14px;border:0;border-radius:10px;background:#1565c0;color:#fff}</style></head><body>"
    "<div class='card'><h1>Garage Door</h1><div class='s' id='d'>...</div><div id='c'>...</div><div id='t'></div>"
    "<input id='p' type='password' placeholder='PIN'><br><button onclick='go()'>Open / Close</button><div id='m'></div></div>"
    "<script>function u(){fetch('/status').then(r=>r.json()).then(j=>{d.textContent=j.door;"
    "c.textContent='Car inside: '+(j.car?'Yes':'No')+(j.cm>0?' ('+j.cm+' cm)':'');"
    "t.textContent=j.openMin>=0?'Open for '+j.openMin+' min':''})}"
    "function go(){fetch('/toggle?pin='+encodeURIComponent(p.value)).then(r=>r.text()).then(x=>{m.textContent=x;u()})}"
    "u();setInterval(u,2000);</script></body></html>");
  server.send(200, "text/html", html);
}

void handleStatus() {
  DoorState s = readDoor();
  long openMin = (s == DOOR_CLOSED) ? -1 : (long)((millis() - openSince) / 60000UL);
  bool car = carDistance > 0 && carDistance < CAR_DISTANCE_CM;
  String json = String("{\"door\":\"") + doorText(s) + "\",\"car\":" + (car ? "true" : "false") +
                ",\"cm\":" + carDistance + ",\"openMin\":" + openMin + "}";
  server.send(200, "application/json", json);
}

void handleToggle() {
  if (server.arg("pin") != DOOR_PIN) {
    server.send(403, "text/plain", "Wrong PIN");
    return;
  }
  bool closing = readDoor() != DOOR_CLOSED;     // warn people before closing
  server.send(200, "text/plain", closing ? "Closing (warning beeps)" : "Opening");
  pulseOpener(closing);
}

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);   digitalWrite(RELAY_PIN, LOW);
  pinMode(BUZZER_PIN, OUTPUT);  digitalWrite(BUZZER_PIN, LOW);
  pinMode(REED_CLOSED, INPUT_PULLUP);
  pinMode(REED_OPEN, INPUT_PULLUP);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);     // D8 has an on-board pull-down

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.print("\nOpen http://"); Serial.println(WiFi.localIP());
  if (MDNS.begin("garage")) Serial.println("or http://garage.local");

  server.on("/", handleRoot);
  server.on("/status", handleStatus);
  server.on("/toggle", handleToggle);
  server.begin();
  if (readDoor() != DOOR_CLOSED) openSince = millis();
}

void loop() {
  server.handleClient();
  MDNS.update();

  static DoorState last = DOOR_CLOSED;
  DoorState now = readDoor();
  if (now != last) {                       // door started opening
    if (last == DOOR_CLOSED) openSince = millis();
    Serial.printf("Door: %s\n", doorText(now));
    last = now;
  }

  if (millis() - lastSonar > 1000) {       // read the car sensor once a second
    lastSonar = millis();
    carDistance = readDistanceCm();
  }

  // Auto-close only when the door is fully open and has been for too long
  if (AUTO_CLOSE_MIN > 0 && now == DOOR_OPEN &&
      millis() - openSince > AUTO_CLOSE_MIN * 60000UL) {
    Serial.println("Auto-close");
    pulseOpener(true);
    openSince = millis();                  // wait a full period before retrying
  }
}

Installation and Testing

  • Test on the bench first: connect a small LED to the relay contacts with a battery, open the page and check that the relay clicks for half a second after the warning beeps.
  • Find the opener’s push-button terminals (usually two screw terminals marked PB, PUSH or WALL). Connect the relay COM and NO there, alongside the existing wall button wires.
  • Stick the closed-position reed switch on the frame and its magnet on the door so they meet when the door is shut. Repeat for the fully-open position near the top of the track.
  • Mount the HC-SR04 on the ceiling above where the car bonnet or roof sits. Check the distance on the page with and without the car and adjust CAR_DISTANCE_CM.
  • Keep the D1 Mini near a good Wi-Fi signal, away from the opener motor, and inside a plastic box.

Troubleshooting

ProblemFix
Relay clicks but the door does not moveMake sure the relay is on the push-button terminals, not the photo-eye terminals. Some openers with coded wall panels need a spare remote’s button wired to the relay instead.
Status always shows “Moving”Bring the magnet closer to the reed switch (under 15 mm) or check the switch is normally open, not normally closed.
Distance reads -1Check the ECHO divider and TRIG wiring, and that the sensor faces a flat surface less than 4 m away.
Board will not bootD8 must not be pulled HIGH at power-up. Keep the 2k resistor from D8 to GND and check the ECHO wire.
Page does not loadUse the IP address from the Serial Monitor; some phones do not support .local names.

Safety Notes

  • Never remove or bypass the opener’s own safety photo-eyes or obstacle reversal. This project only adds a remote button.
  • Keep the web page on your home network. Do not port-forward it to the internet without proper authentication.
  • Change the default PIN in the code before installing.

Ideas to Extend

  • Send a phone alert when the door is left open, using a free push service such as ntfy.
  • Add a DHT22 to show the garage temperature and humidity on the same page.
  • Turn on a garage light relay automatically for 2 minutes whenever the door opens.