int buttonPin = 2; // Pin where the button is connected
int ledPin = 13; // Pin where the built-in LED is connected
int buttonState = 0; // Variable to store the current button state
int lastButtonState = 0; // Variable to store the previous button state
unsigned long lastPressTime = 0; // Time of the last button press
unsigned long debounceDelay = 50; // Delay to avoid button bounce (debouncing)
int blinkCount = 0; // Number of times the LED should blink
void setup() {
pinMode(buttonPin, INPUT); // Set button pin as input
pinMode(ledPin, OUTPUT); // Set LED pin as output
}
void loop() {
// Read the button state
buttonState = digitalRead(buttonPin);
// Check if the button state has changed (debounced)
if (buttonState != lastButtonState) {
lastPressTime = millis(); // Reset the debounce timer
}
// If the button is pressed and enough time has passed (debounced)
if (buttonState == HIGH && millis() - lastPressTime > debounceDelay) {
// Generate a random number (1 or 2) to determine the number of blinks
blinkCount = random(1, 3); // 50% chance for 1 or 2 blinks
// Blink the LED based on the random number
blinkLED(blinkCount);
// After blinking, wait until the button is released before proceeding
while (digitalRead(buttonPin) == HIGH) {
// Keep waiting for button to be released
}
}
lastButtonState = buttonState; // Update the last button state
}
void blinkLED(int times) {
for (int i = 0; i < times; i++) {
digitalWrite(ledPin, HIGH); // Turn LED on
delay(500); // Wait for 500ms
digitalWrite(ledPin, LOW); // Turn LED off
delay(500); // Wait for 500ms
}
}