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

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.

Leave a Comment