E8-9ESP8266Beginner

ESP8266 Button State on a Web Page: Press the Button on the NodeMCU and Your Phone Shows It at Once

Press the button on the breadboard and the web page on your phone says PRESSED and counts the presses. The NodeMCU V3 joins your home Wi-Fi and serves a status page. A small script on the page asks the board for the state three times a second, so the page updates itself without reloading. The button needs no resistor: the code uses the internal pull-up of the board (INPUT_PULLUP) and filters contact bounce with a 30 ms debounce. The ESP8266 only joins 2.4 GHz networks.

0.0(0)
ESP8266 Button State on a Web Page: Press the Button on the NodeMCU and Your Phone Shows It at Once
So far the phone was in charge of the board; in this project the direction turns around and the board reports to the phone. You learn to wire a button without a resistor, to read a press reliably and to keep one press from being counted several times. You also see a web page ask for fresh data by itself. The same method is the basis of door and window sensors, a mailbox alert, a water level warning and every project that watches the state of an input from a distance.

Video

Circuit Diagram

ESP8266 Button State on a Web Page: Press the Button on the NodeMCU and Your Phone Shows It at Once - Circuit Diagram

Source Code

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP8266 Button State on a Web Page: Press the Button on the NodeMCU and Your Phone Shows It at Once
4// ─────────────────────────────────────────
5// The NodeMCU joins your home Wi-Fi and shows the state of a push button
6// on a web page. Open the board's IP address in the browser of a phone on
7// the same network: press the button on the breadboard and the page says
8// pressed and counts the press. The page asks the board for the state
9// three times a second, so it follows the button by itself.
10//
11// Pins:
12//   D5 (GPIO14) -> one leg of the button
13//   GND         -> the other leg of the button (other column)
14
15#include <ESP8266WiFi.h>
16#include <ESP8266WebServer.h>
17
18// ============ WI-FI NETWORK ============
19// Write the name and password of your own network inside the quotes. The ESP8266 only joins 2.4 GHz
20// networks.
21const char *const WIFI_SSID = "YOUR_WIFI_NAME";
22const char *const WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
23const unsigned long WIFI_HINT_MS = 20000; // Time until the hint (ms)
24
25// ============ PINS ============
26// D3, D4 and D8 have a special job while the board starts; a button there can keep the board from
27// booting. The button uses the spare pin D5.
28const uint8_t PIN_BUTTON = D5;            // GPIO14
29const unsigned long DEBOUNCE_MS = 30;     // ms
30
31// ============ PAGE TEXTS ============
32const char TEXT_TITLE[] = "Button State";
33const char TEXT_PRESSED[] = "PRESSED";
34const char TEXT_RELEASED[] = "RELEASED";
35const char TEXT_NOT_FOUND[] = "Page not found";
36
37// ============ WEB PAGE ============
38// The fixed top of the page: UTF-8 encoding, a phone-friendly width and the looks (CSS).
39const char PAGE_HEAD[] = R"rawliteral(<!DOCTYPE html><html><head><meta charset="utf-8">
40<meta name="viewport" content="width=device-width,initial-scale=1"><title>ESP8266</title>
41<style>
42body{margin:0;padding:28px 20px;background:#0f172a;color:#f8fafc;font-family:sans-serif;
43text-align:center}
44h1{font-size:26px;margin:0 0 28px}
45p{max-width:300px;margin:0 auto;padding:44px 0;border-radius:24px;font-size:30px;font-weight:bold;
46background:#334155}
47p.a{display:none;background:#22c55e;color:#0f172a}
48.on p.a{display:block}
49.on p.b{display:none}
50div{font-size:72px;font-weight:bold;margin:28px 0 0;color:#38bdf8}
51</style></head>)rawliteral";
52
53// The script of the page: three times a second it asks the board for /state and gets a short text
54// like 1 7: pressed or not, then the press count. It switches the look of the page and writes the
55// count.
56const char PAGE_SCRIPT[] = R"rawliteral(<script>
57setInterval(function(){
58fetch('/state').then(function(r){return r.text()}).then(function(t){
59document.body.className=t.charAt(0)=='1'?'on':'';
60document.getElementById('n').textContent=t.substring(2);
61})},300);
62</script></body></html>)rawliteral";
63
64ESP8266WebServer server(80);              // Port 80: the web default
65bool pressed = false;
66bool lastReading = false;
67unsigned long lastChange = 0;
68unsigned int pressCount = 0;
69bool wifiUp = false;
70bool hintDone = false;
71
72// Reads the button without waiting. INPUT_PULLUP keeps the pin HIGH; a press connects it to GND, so
73// LOW means pressed. A change only counts once the pin has stayed the same for DEBOUNCE_MS.
74void readButton() {
75  bool reading = digitalRead(PIN_BUTTON) == LOW;
76  if (reading != lastReading) {
77    lastReading = reading;
78    lastChange = millis();
79  }
80  if (reading == pressed || millis() - lastChange < DEBOUNCE_MS) {
81    return;
82  }
83  pressed = reading;
84  if (pressed) {
85    pressCount++;
86    Serial.print("Button pressed: ");
87    Serial.println(pressCount);
88  } else {
89    Serial.println("Button released");
90  }
91}
92
93// Builds the page for the current state and sends it to the browser. Both words are in the page;
94// the looks (CSS) pick the one that shows.
95void sendPage() {
96  String html = PAGE_HEAD;
97  html += pressed ? "<body class=\"on\"><h1>" : "<body><h1>";
98  html += TEXT_TITLE;
99  html += "</h1><p class=\"a\">";
100  html += TEXT_PRESSED;
101  html += "</p><p class=\"b\">";
102  html += TEXT_RELEASED;
103  html += "</p><div id=\"n\">";
104  html += pressCount;
105  html += "</div>";
106  html += PAGE_SCRIPT;
107  // The browser must not keep a copy of the page; every tap has to reach the board.
108  server.sendHeader("Cache-Control", "no-store");
109  server.send(200, "text/html; charset=utf-8", html);
110}
111
112// Every address has its own function; it runs when the browser asks for that address.
113void handleRoot() {
114  sendPage();
115}
116
117// The script asks for this address. The answer is a short text: 1 or 0, a space and the press
118// count.
119void handleState() {
120  String text = pressed ? "1 " : "0 ";
121  text += pressCount;
122  server.sendHeader("Cache-Control", "no-store");
123  server.send(200, "text/plain", text);
124}
125
126void handleNotFound() {
127  server.send(404, "text/plain; charset=utf-8", TEXT_NOT_FOUND);
128}
129
130// Watches the connection: prints the IP address once connected and reports a drop. The ESP8266
131// rejoins a lost network by itself.
132void checkWifi() {
133  bool up = WiFi.status() == WL_CONNECTED;
134  if (up && !wifiUp) {
135    hintDone = true;
136    Serial.println("Wi-Fi connected");
137    Serial.print("Open in your browser: ");
138    Serial.print("http://");
139    Serial.println(WiFi.localIP());
140  } else if (!up && wifiUp) {
141    Serial.println("Wi-Fi lost. Reconnecting");
142  }
143  wifiUp = up;
144
145  if (!up && !hintDone && millis() > WIFI_HINT_MS) {
146    hintDone = true;
147    Serial.println("Could not join the Wi-Fi");
148    Serial.println("Check the network name and password");
149    Serial.println("The ESP8266 only sees 2.4 GHz networks");
150  }
151}
152
153void setup() {
154  Serial.begin(115200);
155  pinMode(PIN_BUTTON, INPUT_PULLUP);
156  Serial.println();
157  Serial.println("Web button state");
158  if (strncmp(WIFI_SSID, "YOUR_", 5) == 0) {
159    Serial.println("Put your Wi-Fi name and password in the code");
160  }
161  Serial.println("Connecting to Wi-Fi");
162  // The board opens no network of its own, it joins yours
163  WiFi.mode(WIFI_STA);
164  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
165
166  server.on("/", handleRoot);
167  server.on("/state", handleState);
168  server.onNotFound(handleNotFound);
169  server.begin();
170}
171
172// loop never waits: a long delay would freeze the page and can drop the Wi-Fi.
173void loop() {
174  checkWifi();
175  readButton();
176  server.handleClient();                  // Handles a waiting request
177}
178

FAQ

Why does the button need no resistor?

An input pin left hanging is unstable: noise makes it read HIGH or LOW at random. INPUT_PULLUP switches on a resistor inside the board that holds the pin HIGH. The other end of the button goes to GND; a press pulls the pin down to GND and it reads LOW. So in this wiring LOW means pressed and HIGH means released, and you do not have to add a resistor yourself.

What is the debounce filter for?

The metal contact inside a button bounces for a few milliseconds when you press and release it; the board is so fast that it can see one press as five or ten. That is why the code does not accept a change right away: it counts once the pin has stayed the same for 30 ms. A person does not notice 30 ms, but all the bouncing is over by then. The time lives in the constant DEBOUNCE_MS.

How far behind the button is the page?

The script on the page asks the board for /state every 300 ms, so the screen is at most a third of a second behind the button. You may not see a very short press turn green on screen, but the counter still goes up, because the board counts the presses, not the page. To shorten the gap, lower the number 300 in the script; going below 100 loads the network for no reason.

Why should I not wire the button to D3, D4 or D8?

These three pins decide in which mode the board starts: D3 and D4 have to be HIGH and D8 has to be LOW. If the button is held down while the board powers up, or pulls the pin to the wrong level, the board may not start at all or may enter upload mode. D5, D6 and D7 have no such job; this project uses D5.