// Define pin numbers
const int buttonPin = 9; // Button connected to digital pin 2
const int ledPin = 7; // LED connected to digital pin 13
// Variables
int buttonState = 0; // Variable to store the button state
int lastButtonState = 0; // Variable to store the last button state
int counter = 0; // Counter for button presses
unsigned long debounceDuration = 50; // Debounce duration in milliseconds
unsigned long lastTimeButtonStateChanged = 0; // Last time button state was changed
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with pull-up resistor
pinMode(ledPin, OUTPUT); // Set LED pin as output
digitalWrite(ledPin, LOW); // Initial state: LED off
Serial.begin(9600); // Start serial communication
}
void loop() {
// Read the state of the button
buttonState = digitalRead(buttonPin);
// Check if the button has been pressed (transition from HIGH to LOW)
if (millis() - lastTimeButtonStateChanged > debounceDuration) {
if (buttonState == LOW && lastButtonState == HIGH) {
// Button has been pressed
counter++;
delay(2000);
Serial.print("Counter: ");
Serial.print(counter);
Serial.print(" << EventNumber: ");
Serial.println(counter%2);
// Check if the counter value is even
if (counter % 2 == 0) {
digitalWrite(ledPin, HIGH); // Turn on the LED if the counter is even
} else {
digitalWrite(ledPin, LOW); // Turn off the LED if the counter is odd
}
lastTimeButtonStateChanged = millis(); // Update the last time button state changed
}
lastButtonState = buttonState; // Save the button state for the next loop iteration
}
}
Restart