/*
https://forum.arduino.cc/t/press-button-and-have-led1-come-on-after-5s-delay-and-led2-simply-turn-on/1261609
*/
unsigned long lastPress = 0; //just my attempt to use millis to achieve this goal somehow
unsigned long intervalDebounce = 50; //just my attempt to use millis to achieve this goal somehow
byte lastBtn = 1;//start high with input pullup
unsigned long lastWait;
unsigned long intervalWait = 5000;
#define BTN_PIN 3 //Push button on D3
#define LED1_PIN 4 //LED 1
#define LED2_PIN 5 //LED 2
int LED1_state = 0;
int LED2_state = 0;
//-----------------------------------------------------------------------
int state = 0; //integer to hold current state
int old = 0; //integer to hold last state
int buttonPoll = 0; //integer to hold button state
//------------------------------------------------------------------------
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP); //button as input activate internal pull up
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
}
//----------------------------------------------------------------------------------
void loop() {
unsigned long now = millis();
if (now - lastPress >= intervalDebounce) {
byte b = digitalRead(BTN_PIN);
if (b != lastBtn) {
lastBtn = b;
lastPress = now;//start debounce
if (b) {
//button press and released..
lastWait = now;
state++;
if (state > 2) state = 1;
Serial.print("Button Press state: ");
Serial.println(state);
}
}
}
switch (state) {
case 1: ////LED1 turns on after 5s delay, and LED2 simply turns on
if (now - lastWait >= intervalWait) {
digitalWrite(LED1_PIN, HIGH); // on after a 5s delay
} else digitalWrite(LED1_PIN, LOW);
digitalWrite(LED2_PIN, HIGH); // on without delay
break;
case 2: ////LED1 simply turns on, and LED2 turns on after a 5s delay
digitalWrite(LED1_PIN, HIGH); // on without delay
if (now - lastWait >= intervalWait) {
digitalWrite(LED2_PIN, HIGH); // on after 5s delay
} else digitalWrite(LED2_PIN, LOW);
break;
default: //// both LED1 and LED2 simply turn on without delay
digitalWrite(LED1_PIN, HIGH); //on without delay (achieved)
digitalWrite(LED2_PIN, HIGH); //on without delay (achieved)
break;
}
}