Beginner here.
I´ve been trying to implement a button function timer working with millis() instead of delay as I want the button to be responsive while the timer is running.
So far I´ve managed to start the counter on the button´s state change and let it time out. Unfortunately all kind of strange behavior is coming out of my sketch and I am yet to understand why.
Help is appreciated.
This is the desired behaviour of the timer:
- On startup the Arduino is ready to recieve a button push. The relay is off (HIGH).
- Once the button is pushed:
• The relay state is changed to LOW in order to turn it on
• A green LED switches on.
• A millis() based timer is switched on. - If the user presses the button while the switch is on, the timer is reset to 0 and continues counting.
- If the on-time is going to end, a red LED starts blinking. Say in the last minute.
- As soon as the timer reaches the specified on-time:
• The green LED switches off
• The relay switches off • The system returns to step 1. and is awaiting a push.
In my code example the red blinking Led is not implemented yet. The following code switches the switch and the green LED on but does not switch them off anymore.
//CONSTANTS
#define BUTTON_PIN 2 // Button
int in1 = 7;
int greenLED = 4;
int redLED = 9;
//VARIABLES
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
//MILLIS
unsigned long previousMillis = 0;
const long interval = 10000;
void setup()
{
pinMode(BUTTON_PIN, INPUT);
digitalWrite(BUTTON_PIN, HIGH); // pull-up
Serial.begin(9600);
pinMode(greenLED, OUTPUT);
pinMode(redLED, OUTPUT);
//SWITCH HANDLERS
pinMode(in1, OUTPUT);
digitalWrite(in1, HIGH);
}
void loop(){
// read the pushbutton input pin:
buttonState = digitalRead(BUTTON_PIN);
unsigned long currentMillis = millis();
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
buttonState = digitalRead(BUTTON_PIN);
if (currentMillis - previousMillis < interval){
//SWITCH ON, LED ON
digitalWrite(in1, LOW);
digitalWrite(greenLED, HIGH);
}
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
digitalWrite(in1, HIGH);
digitalWrite(greenLED, LOW);
}
// Delay a little bit to avoid bouncing
delay(50);
// Reset buttonState:
lastButtonState = buttonState;
}
}