// https://wokwi.com/projects/439190331847941121
const int ButtonPin = 2;
int ButtonState = LOW;
int lastButtonState = LOW;
int ButtonPushCounter = 0;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 25; // 100? get better switches!
void setup() {
//... switch wired to ground, so
pinMode(ButtonPin, INPUT_PULLUP);
Serial.begin(115200);
}
void loop() { // start by pulling from the debounce script,
int reading = digitalRead(ButtonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if (millis() - lastDebounceTime > debounceDelay) {
if (reading != ButtonState) {
ButtonState = reading;
if (ButtonState == LOW) { // iincrement the counter. on press (LOW for my hardware)
ButtonPushCounter++;
if (ButtonPushCounter >= 4) {
ButtonPushCounter = 0;
}
}
}
}
//...
lastButtonState = reading;
static int lastPrinted = -1; // not for long!
if (lastPrinted != ButtonPushCounter) {
Serial.print(" counter is ");
Serial.println(ButtonPushCounter);
lastPrinted = ButtonPushCounter;
}
}