const int buttonPin = 8;
int buttonState = LOW;
int lastButtonState = LOW;
bool buttonToggled = false;
const int ledPin=9;
int ledState = LOW;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Read the current state of the button (HIGH or LOW )
buttonState = digitalRead(buttonPin);
// Check if the button state has changed from its previous state
if(buttonState != lastButtonState) {
// Check if the button is curently pressed(LOW)
if(buttonState == LOW){
//Toggle thr state of the button (ON or OFF)
buttonToggled = !buttonToggled;
ledState = HIGH;
//Print the new toggle state to the serial monitor
if(buttonToggled){
Serial.println("Button is PRESSED");
ledState = HIGH;
}
else {
Serial.println("Button is NOT PRESSED");
ledState = LOW;
}
}
// Add a small delay to debounce the button and avoid false triggers
delay(50);//50 milliseconds debounce delay
}
lastButtonState = buttonState ;
digitalWrite(ledPin,ledState);
}