I am using millis() to flash some lights (neopixels) on an arduino pro mini. The problem is that I cannot flash the lights for the desired period. More specifically, the lights flash for ~250 ms, whereas I want to flash for 9 seconds! Here is a simplified version of what I am doing.
In loop(), I have a while loop (let's call it loop 1) that should run for 250 ms. Inside loop 1, I call a function flash(), that has to run for 9 seconds! I put another loop (loop 2) after loop 1, that would run for 3 seconds.
Here is the bigger picture...I actually want a radio to wake up for 250 ms. If in that time interval it receives anything, flash() will be called that will flash the lights for 9 secs. If it doesn't receive anything it will simply go to sleep for 3 secs, then come back alive for 250 ms, so on and so on
void loop() {
previousMillis = millis();
while (millis() - previousMillis < awake_interval) { //awake_interval = 250 ms
flash(); //flash for 9 seconds
}
previousMillis = millis();
while (millis() - previousMillis < sleep_interval); //sleep_interval = 3 secs
}
The flash() function looks like this,
void flash() {
unsigned long x = millis();
while(millis() - x < flash_time){ //flash_time = 9 secs
lights_on();
delay(t1);
lights_off();
delay(t2);
}
}
I put loop 2 in there because without it the lights flash forever. This makes sense because all the code is in an infinite loop - void loop().
For debugging, I put serial prints after entering the loops. It seems that nesting two loops (in my case flash() inside loop 1), both of which uses millis() is the source of the problem. If that is true, how else should I do this? If that is not the problem, any ideas will be appreciated.
Edit: The suggestions made by @VE7JRO and @ratchet freak are neat but I was still having problems making my thing work. Turns out it was a problem with one my initializations. I am posting my whole code below (that uses LEDs). I guess I should post the correct code as an answer.
const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;
const uint8_t flash_time = 9000; //bug
const uint16_t t1 = 5;
const uint16_t t2 = 495;
void flash() {
unsigned long x = millis();
while(millis() - x < flash_time){
digitalWrite(ledPin, HIGH);
delay(t1);
digitalWrite(ledPin, LOW);
delay(t2);
}
}
void setup() {
Serial.begin(57600);
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long x = millis();
while(millis() - x < awake_interval){
Serial.println("flash time!");
flash(); //overflow will occur
}
unsigned long y = millis();;
while (millis() - y < sleep_interval) { //sleep_interval = 3 secs
Serial.println("Sleep time!");
}
}