🛠 Lire un bouton sur GPIO4 avec l'ESP8266-ESP-12E

ESP8266 (ESP-12E module) · debutant · Schéma : IMG-esp8266-esp-12e-debutant-2-esp8266-bouton-gpio4.svg — Module ESP8266-ESP-12E, bouton poussoir entre GPIO4 et la masse, résistance de pull-up interne activée, console UART0 sur GPIO1/GPIO3.

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials