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

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.

1 thought on “Wemos D1 Mini Bidirectional Visitor Counter with IR Sensors, OLED, Auto Light & Wi-Fi Dashboard”

Leave a Comment