A push button is a simple switch that connects or disconnects a circuit when pressed. With ESP8266, push buttons are used for:
In this tutorial, we’ll learn how to:
We’ll connect the button to GPIO D5 (GPIO14).
👉 This means the button is normally HIGH, and goes LOW when pressed.
int buttonPin = D5; // GPIO14
int buttonState = 0;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP); // Internal pull-up resistor
}
void loop() {
buttonState = digitalRead(buttonPin); // Read button
if (buttonState == LOW) { // Pressed
Serial.println("Button Pressed!");
} else {
Serial.println("Button Released!");
}
delay(200);
}
We’ll use D5 (GPIO14) for button input and D6 (GPIO12) for LED output.
Connections:
(Alternatively, we can use ESP8266’s internal pull-up resistor to skip the external one.)
int buttonPin = D5; // Button pin
int ledPin = D2; // LED pin (GPIO4)
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) { // Button pressed
digitalWrite(ledPin, HIGH); // LED ON
} else {
digitalWrite(ledPin, LOW); // LED OFF
}
}
👉 LED turns ON when button is pressed.
int buttonPin = D5;
int ledPin = D2;
int buttonState;
int lastButtonState = HIGH;
bool ledState = LOW;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW && lastButtonState == HIGH) {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState);
delay(200); // Debounce delay
}
lastButtonState = buttonState;
}
You learned how to:
This is a foundation project for many IoT applications like doorbells, alarms, and smart switches. 🚀
Yes, just assign each button to a separate GPIO pin.
That’s expected if you’re using a pull-up resistor.
Use software debounce (small delay) or a hardware capacitor.