Hello everyone, can anyone help me to fix this code. My operation for my project is when the pushbutton is hold for 3 sec it will turn on the led if not hold for 3 sec the led keep turn off. Then when the led was turn on it will keep to turn on if the pushbutton keep push and led will turn off if I release pushbutton for 3 sec.
this code I got from Use Arduino millis() with buttons to delay events - Bald Engineer
> #include <LiquidCrystal.h>
>
> //Global Variables
> const byte BUTTON = 8; // our button pin
> const byte LED = 9; // LED (built-in on Uno)
>
> unsigned long buttonPushedMillis; // when button was released
> //unsigned long ledTurnedOnAt; // when led was turned on
> unsigned long buttonReleased;
> unsigned long turnOnDelay = 3000; // wait to turn on LED
> unsigned long turnOffDelay = 3000; // turn off LED after this time
> bool ledReady = false; // flag for when button is let go
> bool ledState = false; // for LED is on or not.
> const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
> LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
>
> void setup() {
> pinMode(BUTTON, INPUT_PULLUP);
> pinMode(LED, OUTPUT);
> digitalWrite(LED, LOW);
> lcd.setCursor(0, 1);
> lcd.print("RUNNING!! ");
> Serial.begin (9600);
>
> }
>
> void loop() {
> // get the time at the start of this loop()
> unsigned long currentMillis = millis();
>
> // check the button
> if (digitalRead(BUTTON) == LOW) {
> // update the time when button was pushed
> buttonPushedMillis = currentMillis;
> ledReady = true;
> }
>
> // make sure this code isn't checked until after button has been let go
> if (ledReady) {
> //this is typical millis code here:
> if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
> // okay, enough time has passed since the button was let go.
> digitalWrite(LED, HIGH);
> lcd.setCursor(0, 1);
> lcd.print("LF PRESENT!!");
> // setup our next "state"
> ledState = true;
> // save when the LED turned on
>
> buttonReleased = currentMillis;
> // wait for next button press
> ledReady = false;
>
> }
> }
>
> // see if we are watching for the time to turn off LED
> if (ledState) {
> // okay, led on, check for now long
>
> if ( (unsigned long)(currentMillis - buttonReleased) >= turnOffDelay) { //if the button release it will hold led on in 3 sec then back to running
>
>
> ledState = false;
> digitalWrite(LED, LOW);
> lcd.setCursor(0, 1);
> lcd.print("RUNNING!! ");
>
> }
>
> }
> }