// Define pin numbers
const int buttonPin = 12;
const int ledPin = 32;
// Variables to track button state and LED state
int buttonState = 0;
int lastButtonState = LOW; // Track the previous button state for edge detection
int ledState = LOW; // Initially off
// Timing variables for debouncing
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50; // Debounce time in milliseconds
void setup() {
// Set pin modes
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(115200); // Initialize serial communication for debugging (optional)
}
void loop() {
// Read the button state
int reading = digitalRead(buttonPin);
// Check for button press (edge detection)
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset the debouncing timer
}
// Check if the debounce time has elapsed
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed, update the LED state
if (reading != buttonState) {
buttonState = reading;
// Only toggle the LED if the button is pressed (not released)
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
// Optional: Print the LED state to the Serial Monitor for debugging
Serial.print("LED is now ");
Serial.println(ledState == HIGH ? "ON" : "OFF");
}
}
}
lastButtonState = reading; // Update the previous button state
}