Last updated March 2023
How I wire a button with either 2 or 4 pins with ESP32 boards. (This works with an ESP8266 too.)
This example uses the D25 pin to power the button, but you can also use the 3.3V pin instead.
If powering the button with the 3.3V pin, omit the lines referencing BUTTON_PIN_POWER
#define BUTTON_PIN_POWER 25
#define BUTTON_PIN_DATA 27 // omit if using 3.3V pin
void setup() {
Serial.begin(115200);
delay(100);
pinMode(BUTTON_PIN_POWER, OUTPUT);
pinMode(BUTTON_PIN_DATA, INPUT);
}
void loop() {
digitalWrite(BUTTON_PIN_POWER, HIGH);
int buttonRead = digitalRead(BUTTON_PIN_DATA); // HIGH when button held
if (buttonRead == HIGH) {
Serial.println("ON");
} else {
Serial.println("OFF");
}
delay(100);
}