/*
Hold a button for a period, when released prior to the period abort.
Uses millis() to keep track of time (milliseconds)
https://www.norwegiancreations.com/2017/09/arduino-tutorial-using-millis-instead-of-delay/
Author: F. van Slooten
*/
#include <U8g2lib.h>
#define START_BTN 4
U8X8_SSD1306_128X64_NONAME_HW_I2C display(U8X8_PIN_NONE);
int period = 5000; // time to hold the button
unsigned long time_start = 0;
int status = 0; // 0: checking hold, 1: button succesfully holded, 2: aborted
void setup() {
Serial.begin(9600);
pinMode(START_BTN, INPUT_PULLUP); // start button, without resistor (internal pull-up)
display.begin();
display.setPowerSave(0);
display.setFont(u8x8_font_pxplusibmcgathin_f);
display.drawString(0, 0, "PRESS TO START");
// wait until button pressed to proceed:
// (this while statement halts the program, until the button is pressed)
while (digitalRead(START_BTN) == HIGH) ; // note the empty statement: ';' does nothing, thus waits for START_BTN to be pressed (becomes LOW)
display.clearLine(0);
display.drawString(0, 0, "HOLD");
time_start = millis(); // start time
delay(200);
}
void loop() {
if (status > 0) {
return; // do nothing if status > 0
}
else { // status == 0, we are checking if the button is being held
if (millis() >= time_start + period) { // holding period over?
display.clearLine(0);
display.drawString(0, 0, "DONE"); // time to hold the button for period succesfully done
status = 1;
}
else if (digitalRead(START_BTN) == HIGH) { // button released?
// abort, button was released
display.clearLine(0);
display.drawString(0, 0, "ABORT");
status = 2;
}
}
}