Hello All!!! I've been playing with this code for some time and still have not found a way to manage to get 1 input to control multiple outputs based on StateChange of the button. In english what I'm trying to achieve...
- 1st Press (LED1 == HIGH)
- 2nd Press (LED1 and LED2 == HIGH)
- 3rd Press or 5000 milliseconds (LED1 and LED2 == LOW) (back to start)
- Was also hoping for a timeout function after 2nd Press that would loop back to start. So either 3rd press or timeout of 5000 milliseconds would restart the loop.
My research has taken me to "Counting Button Presses" "Different Cases according to which press we're on" and Just state change in general because it is such a short loop.
I think the simplicity of the program is eating at my complexity lol.
Thank you all so much in advance for helping me understand what direction to take!
#define LED_1_PIN 8
#define LED_2_PIN 9
#define BUTTON_PIN 1
unsigned long debounceDuration = 50; // millis
unsigned long lastTimeButtonStateChanged = 0;
byte lastButtonState = HIGH;
void setup(){
pinMode(LED_1_PIN, OUTPUT);
pinMode(LED_2_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop(){
unsigned long timeNow = millis();
if (timeNow - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = timeNow;
lastButtonState = buttonState;
if (buttonState == HIGH) { // button has been released
digitalWrite(LED_1_PIN, HIGH);
}
else if (timeNow - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = timeNow;
lastButtonState = buttonState;
if (buttonState == HIGH) { // button has been released
digitalWrite(LED_1_PIN, HIGH);
digitalWrite(LED_2_PIN, HIGH);
}
else if (timeNow - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = timeNow;
lastButtonState = buttonState;
if (buttonState == HIGH) { // button has been released
digitalWrite(LED_1_PIN, LOW);
digitalWrite(LED_2_PIN, LOW);
}
}
}
}
}
}
}
}
This Set-Up is turning the LED on with the 1st PRESS, but NOT turning both on with 2nd PRESS, and NOT resetting with 3rd PRESS. I haven't jumped into the 5000 milllis yet... just trying to get a grasp before adding the timeout function.
Thanks again all!