const int buttonPin = 2; // Replace with the actual pin number where your button is connected
int counter = 0;
unsigned long lastMillis = 0;
unsigned long interval = 200;
bool buttonState = false;
unsigned long buttonPressedTime = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as an input with a pull-up resistor
Serial.begin(115200);
Serial.print("Counter: ");
Serial.println(counter);
}
void loop(){
checkButton();
}
void checkButton() {
unsigned long currentMillis = millis();
int reading = digitalRead(buttonPin);
if (reading == LOW && !buttonState) {
// Button was just pressed
buttonState = true;
buttonPressedTime = currentMillis;
}
if (buttonState) {
if (currentMillis - buttonPressedTime >= 1000) {
// Button has been held for 1 second, halve the interval
interval /= 2;
buttonPressedTime = currentMillis;
}
if (currentMillis - lastMillis >= interval) {
// Increment the counter every 'interval' milliseconds
counter++;
lastMillis = currentMillis;
Serial.print("Counter: ");
Serial.println(counter);
}
}
if (reading == HIGH && buttonState) {
// Button was just released
buttonState = false;
interval = 200; // Reset the interval to 200ms
}
}