🛠 Lire un bouton sur GPIO4 avec l'ESP8266-ESP-12E
Objectives
Learn how to read a digital input on the ESP8266-ESP-12E using a push button on GPIO4 (pin D2 on NodeMCU boards). GPIO4 is one of the "safe" pins on the module, along with GPIO5: they have no startup constraints, unlike GPIO0, GPIO2, and GPIO15. We enable the internal pull-up resistor (approximately 45 kΩ) using INPUT_PULLUP, which avoids adding an external resistor: the button connects the pin to ground when pressed, so the input reads LOW. We display button presses on the UART0 serial console at 115200 bauds, and discover the role of yield to feed the software watchdog.
Hardware
- 1 ESP8266-ESP-12E module (or NodeMCU / Wemos D1 Mini board)
- 1 push button
- 1 onboard LED (GPIO2) or external LED with a 330 Ω resistor
- Stable 3.3 V power supply (recommended peak current ≥ 500 mA)
- USB-to-serial cable (CP2102/CH340) for the console
Complete code
// Bouton sur GPIO4 (D2), LED sur GPIO2 (D4, active-LOW sur la plupart des modules)
const uint8_t BTN = 4;
const uint8_t LED = 2;
void setup {
pinMode(BTN, INPUT_PULLUP); // pull-up interne ~45 kΩ, pas de résistance externe
pinMode(LED, OUTPUT);
Serial.begin(115200); // console sur UART0 : GPIO1 TX / GPIO3 RX
Serial.println("Pret : appuyez sur le bouton GPIO4");
}
void loop {
static uint8_t last = HIGH;
uint8_t now = digitalRead(BTN);
if (now != last) { // anti-rebond logiciel simple
delay(30);
now = digitalRead(BTN);
if (now != last) {
last = now;
Serial.println(last == LOW ? "Bouton APPUYE" : "Bouton lache");
}
}
digitalWrite(LED, last); // LED embarquée s'allume quand on appuie (active-LOW)
yield; // nourrit le watchdog logiciel (WDT)
}
Expected verification
Open the serial monitor at 115200 bauds and reset the module: the welcome message is displayed. Each time the button is pressed, the console displays "Button PRESSED" and the LED turns on; each time it is released, "Button released" is displayed and the LED turns off. No unexpected resets should occur: if they do, suspect a weak power supply rather than the code.
Common errors
- Forgetting INPUT_PULLUP and leaving the pin floating: the input picks up noise and displays phantom presses.
- Wiring the button between GPIO4 and 3.3 V with INPUT_PULLUP: this shorts out the pull-up; with this wiring, you need INPUT mode and an external pull-down resistor.
- Using GPIO6 to GPIO11: these pins are connected to the module's internal flash, causing the program to crash or fail to start.
- Running a long blocking loop without yield: the software watchdog (WDT) triggers a reset after a few seconds.
- Pressing the button during boot: GPIO4 has no constraints, but this is true for GPIO0/GPIO2 — check this before concluding it's a bug.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinorespiration.inoArduinodht11.inoArduinoluxmetre.inoArduinoserveur-web.inoArduino