/*
Forum: https://forum.arduino.cc/t/speed-measurement-via-button/1213924
Wokwi: https://wokwi.com/projects/387533742096207873
2024/01/21
ec2021
*/
const byte buttonPin = 4;
unsigned long lastPressedTime = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("Start ");
}
void loop() {
if (buttonPressed()){
if (lastPressedTime > 0){
unsigned long difference = millis()-lastPressedTime;
Serial.print("Time difference: ");
Serial.println(difference);
}
lastPressedTime = millis();
}
}
boolean buttonPressed(){
static unsigned long lastChange = 0;
static byte lastState = LOW;
static byte state;
byte actState = digitalRead(buttonPin);
if (actState != lastState) {
lastState = actState;
lastChange = millis();
}
if (state != actState && millis()-lastChange > 20){
state = actState;
return !state; // Returns true only when state changes from HIGH to LOW
}
return false;
}