How do I run a loop for a specific amount of time?
Here is an example that will run for 5 minutes. Note that the loop will begin executing anytime before the time limit is up, including 1 msec before; it can't cut-off something happening at the 5-minute mark, meaning the timing precision will be limited to the duration of the code in the loop.
Update: My first suggestion had a bug related to the 50-some-odd days roll-over period of the millis() clock. This one is more robust:
uint32_t period = 5 * 60000L; // 5 minutes
for( uint32_t tStart = millis(); (millis()-tStart) < period; ){
doStuff();
moreStuff();
}
You can use a variable that is incremented each time you perform the loop, then you need only to change the loop from using a for
to a while
.
For example:
int incremented_variable = 0;
int incremented_value = 100;
int max_value = 1000;
while(incremented_variable < max_value){
if (kill() == true){ break; }
strip.setPixelColor(1, strip.Color(random(100,255),random(100,255),random(100,255)));
strip.show();
tone(TONE, notes[random(0,3)]);
delay(100);
incremented_variable = incremented_variable + incremented_value;
}
EDIT: I have just read your update on the question.
You can then use a while with a boolean flag that help you to end the loop or if you prefer, you can keep track of the time by calling the method: millis()
.
Using this example:
http://playground.arduino.cc/Code/ElapsedMillis
You could try something like:
#include <elapsedMillis.h>
elapsedMillis timeElapsed;
unsigned int interval = 60000; //one minute in ms
while(timeElapsed < interval){
//do stuff
}
Depending on how accurate you want to be, you might want to opt for a similar method using the RTC.