// Sketch: Arduino - push button switch - time pressed 001
// Show the time a button switch has been pressed
// www.martyncurrey.com
// Pins
// D12 to push button switch with 10K ohm pull down resistor
// tester le 8/11/24, source: https://www.martyncurrey.com/ardiuino-time-a-push-button-switch/
//FONCTIONNE: OUI
const int PIN_PUSH_BUTTON_SWITCH = 12;
// variables
// switch status. Current and previous
boolean oldSwitchState = LOW;
// extra variables used for debounce
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
// timer to record how long the switch is closed
long timer_timeStart = 0;
long timer_timeStop = 0;
void setup()
{
Serial.begin(9600);
Serial.print("Sketch: "); Serial.println(__FILE__);
Serial.print("Uploaded: "); Serial.println(__DATE__);
Serial.println(" ");
pinMode(PIN_PUSH_BUTTON_SWITCH, INPUT);
}
void loop()
{
// simple debounce
newSwitchState1 = digitalRead(PIN_PUSH_BUTTON_SWITCH); delay(1);
newSwitchState2 = digitalRead(PIN_PUSH_BUTTON_SWITCH); delay(1);
newSwitchState3 = digitalRead(PIN_PUSH_BUTTON_SWITCH);
// if all are the same value then we have a reliable reading
if ( (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
{
// check to see if the switch state has changed.
// This can be OPEN to CLOSED or CLOSED to OPEN.
if (newSwitchState1 != oldSwitchState)
{
// OPEN to CLOSED
if ( oldSwitchState == LOW && newSwitchState1 == HIGH )
{
// the switch has just been closed / button has been pressed.
// start the timer
timer_timeStart = millis();
Serial.print("Key pressed. ");
}
// CLOSED toOPEN
if ( oldSwitchState == HIGH && newSwitchState1== LOW )
{
// switch is OPEN and was CLOSED last time.
// stop timer and print the time the button was pressed
timer_timeStop = millis();
Serial.print("Key was pressed for ");
Serial.print(timer_timeStop - timer_timeStart );
Serial.println(" ms");
}
oldSwitchState = newSwitchState1;
} // if (switchState != oldSwitchState)
} // if ( (newSwitchState1==newSwitchState2) && (newSwitchState1==newSwitchState3) )
} // loop