Hi, I'm a new Arduino owner and programmer and I need some help with an timer.
I want to do a program to execute some actions and one for a determined time (for example: 5 minutes) as open a valve, but while the valve is open (for the 5 minutes) I want the Arduino doing other actions like update the informations on the LCD display, blink a LED,... How can I use a timer without using delay function?
I've tried the millis funcition, but it counts the time that the program started and I don't know exactly how to use it.
MorganS:
The subtraction is important. Don't add times. Using subtraction will prevent the "rollover error".
No, you just get a different rollover error. If lastTime is ULONG_MAX and thisTime is 0 (one millisecond later), then thisTime - lastTime will instead have you thinking that ~50 days have elapsed. But I guess just about everybody is happy to experience that once-in-50-days time-warp, because just about everybody implements it.
But when I put a if clause before the millis the problem starts...
void loop() {
// put your main code here, to run repeatedly:
int buttonStatus = digitalRead(4);
if(buttonStatus == 1){
unsigned long currentMillis;
unsigned long previousMillis = 0;
currentMillis = millis();
if((unsigned long)(currentMillis - previousMillis) < 5000){
digitalWrite(2,HIGH);
previousMillis = millis();
}
else{
digitalWrite(2,LOW);
}
}
}
If I press the button before 5 secs after the reset, the LED lights up and not turn off. If I press the button after 5 secs since the last reset nothing happens.
jaholmes:
If lastTime is ULONG_MAX and thisTime is 0 (one millisecond later), then thisTime - lastTime will instead have you thinking that ~50 days have elapsed.
Remember you are going through loop() a zillion times a second. Just look at the clock on your way through. Then you can look at it a lot without blocking.
Jim Lee I'm sorry, but I got a little confused... What's wrong? Or better asking, what I should do in the code above?
I'm a complete newbie and I'm sorry if sometimes I get stuck or keep asking the same thing... =(