/* Question 01
Write a program using ESP32 to toggle an LED to on / off connected
to GPIO5 based on button press connected to GPIO4.
Button Press should switch the LED ON, on release the LED should be
switched off.
Also print the state of the button & LED on the serial monitor.
*/
// Define pin connections
const int buttonPin = 4; // GPIO4 where the button is connected
const int ledPin = 5; // GPIO5 where the LED is connected
// Variables to store the current state of the button and LED
int buttonState = 0;
int lastButtonState = 0;
bool ledState = false;
void setup() {
// Initialize serial communication at 115200 baud
Serial.begin(115200);
// Set the button pin as input
pinMode(buttonPin, INPUT);
// Set the LED pin as output
pinMode(ledPin, OUTPUT);
// Initialize the LED to be off
digitalWrite(ledPin, LOW);
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button is pressed
if (buttonState == HIGH && lastButtonState == LOW) {
// Button is pressed
ledState = true; // Turn on the LED
Serial.println("Button pressed: LED ON");
} else if (buttonState == LOW && lastButtonState == HIGH) {
// Button is released
ledState = false; // Turn off the LED
Serial.println("Button released: LED OFF");
}
// Update the lastButtonState
lastButtonState = buttonState;
// Set the LED state
digitalWrite(ledPin, ledState ? HIGH : LOW);
// Short delay to debounce the button press
delay(50);
}