E8-10ESP8266Beginner

ESP8266 Web Doorbell: Tap the Bell on Your Phone and the NodeMCU Plays Ding Dong

Tap the round bell button on a web page and the buzzer on your breadboard plays ding dong twice. The NodeMCU V3 joins your home Wi-Fi and serves a doorbell page; any phone on the same network can ring it. The melody is timed with millis, not delay, so the board keeps answering the page while it plays, and the page counts how many times the bell has rung. The buzzer must be a passive one: an active buzzer makes a single sound. The ESP8266 only joins 2.4 GHz networks.

0.0(0)
ESP8266 Web Doorbell: Tap the Bell on Your Phone and the NodeMCU Plays Ding Dong
In the earlier projects the board lit LEDs; in this one it makes sound. You learn how a square wave becomes a note, how to write a melody as two lists (pitch and length) and how to play it without stopping the rest of the program. You also see why a tap that arrives while the bell is ringing is ignored and how the page returns to normal by itself. The same method is the base of alarm sounds, beeping timers, wireless doorbells and every project that has to make a sound while it keeps doing something else.

Video

Circuit Diagram

ESP8266 Web Doorbell: Tap the Bell on Your Phone and the NodeMCU Plays Ding Dong - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 Web Doorbell: Tap the Bell on Your Phone and the NodeMCU Plays Ding Dong
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and serves a doorbell page. Open the
6// board's IP address in the browser of a phone on the same network and tap
7// the bell: the buzzer plays ding dong twice. The melody is timed with
8// millis, not delay, so the board keeps answering the page while it plays.
9//
10// Pins:
11//   D5 (GPIO14) -> passive buzzer plus (+) leg
12//   GND         -> passive buzzer other leg
13
14#include <ESP8266WiFi.h>
15#include <ESP8266WebServer.h>
16
17// ============ WI-FI NETWORK ============
18// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
19// networks.
20const char *const WIFI_SSID = "YOUR_WIFI_NAME";
21const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
22const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
23
24// ============ PINS ============
25// D3, D4 and D8 have a special job while the board starts; the buzzer uses the spare pin D5.
26const uint8_t PIN_BUZZER = D5;            // GPIO14
27
28// ============ MELODY ============
29// The frequency (Hz) and the length (ms) of every note. 0 Hz is a rest. tone needs a passive
30// buzzer; an active one only makes a single sound.
31const unsigned int NOTE_HZ[] = {659, 523, 0, 659, 523};
32const unsigned long NOTE_MS[] = {300, 500, 200, 300, 500};
33const uint8_t NOTE_COUNT = 5;
34
35// ============ PAGE TEXTS ============
36const char TEXT_TITLE[] = "Doorbell";
37const char TEXT_RING[] = "RING";
38const char TEXT_NOT_FOUND[] = "Page not found";
39
40// ============ WEB PAGE ============
41// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
42const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
43<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
44<style>
45body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
46text-align:center}
47h1{font-size:26px;margin:0 0 28px}
48a{display:block;width:240px;height:240px;margin:0 auto;border-radius:50%;background:#334155;
49color:#f8fafc;font-size:28px;font-weight:bold;line-height:240px;text-decoration:none}
50a.on{background:#facc15;color:#0f172a}
51p{font-size:56px;font-weight:bold;margin:24px 0 0;color:#38bdf8}
52</style></head><body>)rawliteral";
53
54ESP8266WebServer server(80);              // Port 80: the web default
55bool ringing = false;
56uint8_t noteIndex = 0;
57unsigned long noteStart = 0;
58unsigned int ringCount = 0;
59bool wifiUp = false;
60bool hintDone = false;
61
62// Starts the current note: tone keeps switching the pin at that frequency until it is told
63// otherwise. A rest turns the sound off.
64void startNote() {
65  if (NOTE_HZ[noteIndex] > 0) {
66    tone(PIN_BUZZER, NOTE_HZ[noteIndex]);
67  } else {
68    noTone(PIN_BUZZER);
69  }
70  noteStart = millis();
71}
72
73// Builds the page and sends it to the browser: the bell button and how many times it has rung.
74void sendPage() {
75  String html = PAGE_HEAD;
76  html += "<h1>";
77  html += TEXT_TITLE;
78  html += ringing ? "</h1><a class=\"on\" href=\"/ring\">" : "</h1><a href=\"/ring\">";
79  html += TEXT_RING;
80  html += "</a><p>";
81  html += ringCount;
82  html += "</p></body></html>";
83  // The browser must not keep a copy of the page; every tap has to reach the board.
84  server.sendHeader("Cache-Control", "no-store");
85  // While the bell rings the browser reloads the page two seconds later; the button goes back to
86  // normal.
87  if (ringing) {
88    server.sendHeader("Refresh", "2");
89  }
90  server.send(200, "text/html; charset=utf-8", html);
91}
92
93// An address that has done its job sends the browser back to the root page (303). The address bar
94// always shows / and reloading the page does not repeat the last tap.
95void goHome() {
96  server.sendHeader("Location", "/");
97  server.send(303);
98}
99
100// Every address has its own function; it runs when the browser asks for that address.
101void handleRoot() {
102  sendPage();
103}
104
105// The bell button: starts the melody at the first note. A tap while it is playing changes nothing.
106void handleRing() {
107  if (!ringing) {
108    ringing = true;
109    noteIndex = 0;
110    ringCount++;
111    startNote();
112    Serial.print("Doorbell rang: ");
113    Serial.println(ringCount);
114  }
115  goHome();
116}
117
118void handleNotFound() {
119  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
120}
121
122// The clock of the melody: moves on to the next note once the current one has had its time and goes
123// silent after the last one. It never waits, it only looks at the time that has passed, so loop
124// keeps turning and the page keeps working.
125void runMelody() {
126  if (!ringing || millis() - noteStart < NOTE_MS[noteIndex]) {
127    return;
128  }
129  noteIndex++;
130  if (noteIndex >= NOTE_COUNT) {
131    ringing = false;
132    noTone(PIN_BUZZER);
133    return;
134  }
135  startNote();
136}
137
138// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
139// rejoins a lost network by itself.
140void checkWifi() {
141  bool up = WiFi.status() == WL_CONNECTED;
142  if (up && !wifiUp) {
143    hintDone = true;
144    Serial.println("Wi-Fi connected");
145    Serial.print("Open in your browser: ");
146    Serial.print("http://");
147    Serial.println(WiFi.localIP());
148  } else if (!up && wifiUp) {
149    Serial.println("Wi-Fi lost. Reconnecting");
150  }
151  wifiUp = up;
152
153  if (!up && !hintDone && millis() > WIFI_HINT_MS) {
154    hintDone = true;
155    Serial.println("Could not join the Wi-Fi");
156    Serial.println("Check the network name and password");
157    Serial.println("The ESP8266 only sees 2.4 GHz networks");
158  }
159}
160
161void setup() {
162  Serial.begin(115200);
163  pinMode(PIN_BUZZER, OUTPUT);
164  digitalWrite(PIN_BUZZER, LOW);
165  Serial.println();
166  Serial.println("Web doorbell");
167  if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
168    Serial.println("Put your Wi-Fi name and password in the code");
169  }
170  Serial.println("Connecting to Wi-Fi");
171  // The board opens no network of its own, it joins yours
172  WiFi.mode(WIFI_STA);
173  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
174
175  server.on("/", handleRoot);
176  server.on("/ring", handleRing);
177  server.onNotFound(handleNotFound);
178  server.begin();
179}
180
181// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
182void loop() {
183  checkWifi();
184  runMelody();
185  server.handleClient();                  // Handles a waiting request
186}
187

FAQ

Why does the buzzer have to be passive?

A passive buzzer is a tiny speaker: it makes whatever frequency the pin sends, so tone can play different notes. An active buzzer has its own circuit inside and makes one fixed sound as soon as it gets power; with it you hear the same beep for every note. Passive ones usually have an open bottom where a green circuit board shows; active ones are sealed underneath and most carry a sticker on top.

Why is the melody timed with millis and not delay?

The melody lasts 1.8 seconds. With delay the board would do nothing else in that time: the page would not open and the phone would wait. Here the code only notes the moment a note started; loop turns thousands of times a second and checks whether the note has had its time. Between those checks the board answers the browser, so the page opens at once even in the middle of the melody.

What happens if I tap again while the bell is ringing?

Nothing changes: the melody carries on and the counter does not go up. The code starts a new melody only when none is playing; otherwise two people tapping at the same time would keep restarting it. The page still answers, it simply sends you back to the main page. The first tap after the melody ends rings the bell again.

How do I change the melody?

The notes live in two lists: NOTE_HZ holds the frequency of every note and NOTE_MS its length in milliseconds; 0 Hz is a rest. Write your own values, keep both lists the same length and set NOTE_COUNT to that length. For example 523, 659, 784 gives a rising do mi sol. If the melody gets longer than two seconds, raise the number in the Refresh header as well; the page has to reload after the melody ends.