Please look at the below example,
#define buttonPin 12
#define ledPin 13
#define DEBOUNCE_PERIOD 10 // 10 milliseconds
#define TIME_DELAY 3000 // 3000 milliseconds
enum state_t : bool {STOP, START};
bool enable;
unsigned long startTime;
unsigned long currTime;
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
Serial.println("Press the PB!");
}
void loop() {
if (enable) {
currTime = millis();
if (currTime - startTime >= TIME_DELAY) {
enable = false;
Action(STOP);
}
} else {
if (isPressed()) {
startTime = millis();
enable = true;
Action(START);
}
}
}
void Action(state_t value) {
switch (value) {
case START:
digitalWrite(ledPin, HIGH);
Serial.println("Delay Time:\t" + String(TIME_DELAY) + " milliseconds.");
break;
default: // case STOP:
digitalWrite(ledPin, LOW);
Serial.println("Elapsed Time:\t" + String(currTime - startTime) + " milliseconds.\n");
Serial.println("Press the PB!");
break;
}
}
bool isPressed() {
static bool buttonState;
static bool input;
static unsigned long startDebounceTime;
bool prevInput = input;
input = digitalRead(buttonPin);
if (input != prevInput) {
startDebounceTime = millis();
}
if (input != buttonState) {
if (millis() - startDebounceTime >= DEBOUNCE_PERIOD) {
buttonState = input;
return buttonState == LOW; // When pressed, state = LOW if pin mode = INPUT_PULLUP, and state = HIGH if pin mode = INPUT.
}
}
return LOW;
}
