unsigned long startMillis;
unsigned long currentMillis;
const unsigned long period = 5000; // Period during which button input is valid
const byte buttonPin1 = A1; // Button on pin A1
byte currentButtonState;
byte previousButtonState = HIGH; // Initialize to HIGH since the button is inactive by default
int count = 0;
boolean counting = true;
unsigned long debounceTime = 50; // Debounce time in milliseconds
unsigned long lastDebounceTime = 0; // Last time the button state changed
void setup()
{
Serial.begin(115200);
pinMode(buttonPin1, INPUT_PULLUP);
Serial.println("Press the button as many times as possible in 5 seconds");
startMillis = millis(); // Save the start time
}
void loop()
{
currentMillis = millis();
if (currentMillis - startMillis <= period) // Check if we're still within the 5-second period
{
int reading = digitalRead(buttonPin1);
// If the button state changes, reset the debounce timer
if (reading != previousButtonState)
{
lastDebounceTime = currentMillis;
}
// If the state remains stable for debounceTime, update the button state
if ((currentMillis - lastDebounceTime) > debounceTime)
{
if (reading != currentButtonState)
{
currentButtonState = reading;
// If the button becomes pressed (LOW state), increment the count
if (currentButtonState == LOW)
{
count++;
Serial.println(count);
}
}
}
// Update the previous button state
previousButtonState = reading;
}
else // Period has ended
{
if (counting)
{
Serial.print("Time is up. Total count: ");
Serial.println(count);
counting = false; // Prevent displaying the message repeatedly
}
}
}