/**
   Turn on a device by holding on/off button for 3 seconds
   https://home.et.utwente.nl/slootenvanf/2020/06/08/countdown-timers-tasks-in-parallel/
   
   Uses libraries:
   U8g2 https://github.com/olikraus/u8g2
    - U8X8 reference: https://github.com/olikraus/u8g2/wiki/u8x8reference
   Bounce2 https://github.com/thomasfredericks/Bounce2
*/
#include <Bounce2.h>
#include <U8g2lib.h>

// display setup:
U8X8_SSD1306_128X64_NONAME_HW_I2C display(U8X8_PIN_NONE);

char buf[10]; // text buffer; to be able to use draw2x2String to show the value

byte button_pins[] = { 4 }; // button pins

#define NUMBUTTONS sizeof(button_pins)

Bounce * buttons = new Bounce[NUMBUTTONS];

int time_fell = 0, t = 0; // counting the time for holding the on/off button
boolean on = false; // determines if device is on or off

void setup() {
  Serial.begin(9600); // make sure speed of Serial Monitor matches this speed

  Serial.print("Button checker with ");
  Serial.print(NUMBUTTONS, DEC);
  Serial.println(" buttons");

  // initialize display:
  display.begin();
  display.setPowerSave(0);

  display.setFont(u8x8_font_pxplusibmcgathin_f);
  display.clear();

  // Make input & enable pull-up resistors on switch pins
  for (int i = 0; i < NUMBUTTONS; i++) {
    buttons[i].attach( button_pins[i] , INPUT_PULLUP  );       //setup the bounce instance for the current button
    buttons[i].interval(25);              // interval in ms
  }
}


void loop() {
  check_buttons();

  if (on) {
    // do other stuff if device is on
  }
}


////////// extra functions: //////////


void check_buttons() {
  // process button press:
  for (int i = 0; i < NUMBUTTONS; i++) {
    // Update the Bounce instance:
    buttons[i].update();
    if ( buttons[i].fell() ) { // button fell
      Serial.print(i);
      Serial.println(" fell");
      display.clearLine(i);
      display.drawString(0, i, "0");

      time_fell = millis(); // record the time it fell
    } else if ( buttons[i].rose() ) { // button rose
      Serial.print(i);
      Serial.println(" rose");
      display.clearLine(i);
      display.drawString(0, i, "1");
      time_fell = 0;
    }
  }

  if (time_fell > 0) { // are we counting for holding the on/off button?
    t = millis();
    if (t - time_fell > 3000) { // is the time after fell larger than 3 seconds?
      // turn on/off:
      display.clearLine(7);
      on = !on;
      if (on) {
        display.drawString(0, 7, "ON"); // show that the device is turned on
      } else {
        display.drawString(0, 7, "OFF"); // show that the device is turned off
        // instead of this, you might want to clear the display (so it looks like the device is turned off)
      }
      time_fell = 0;
    }
  }
}
$abcdeabcde151015202530354045505560fghijfghij