int x = 0;
const int buttonPin = 26;
const int ledPin = 27;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50; // 50 milliseconds debounce delay
int lastButtonState = LOW; // the previous reading from the input pin
int buttonState = LOW;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
// Check if the button state has changed
if (reading != lastButtonState) {
lastDebounceTime = millis(); // reset the debounce timer
}
// If the reading is stable for the debounce delay, consider it as a stable state
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
// Update x based on the button state
if (buttonState == HIGH) {
x = 1; // Button pressed
} else {
x = 0; // Button not pressed
}
Serial.println(x); // Print the button state
}
}
// Control the LED based on the value of x
if (x == 1) {
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
lastButtonState = reading; // Save the current reading
}