#include <Arduino.h>
// Pin where the push button is connected
const int buttonPin = 4;
// Pin where the LED is connected
const int ledPin = 2;
void setup() {
// Set button pin as INPUT with INTERNAL PULL-UP resistor
// The internal resistor connects the pin to VCC (HIGH) by default.
// This prevents the pin from "floating" (random readings).
pinMode(buttonPin, INPUT_PULLUP);
// Set LED pin as OUTPUT
pinMode(ledPin, OUTPUT);
}
void loop() {
// Read the current state of the button
int buttonState = digitalRead(buttonPin);
// IMPORTANT:
// Because we use INPUT_PULLUP:
// - NOT pressed -> HIGH (connected internally to VCC)
// - Pressed -> LOW (button connects pin to GND)
if (buttonState == LOW) { // Button is pressed
digitalWrite(ledPin, HIGH); // Turn LED ON
} else { // Button is not pressed
digitalWrite(ledPin, LOW); // Turn LED OFF
}
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4