Hello,
I need to run a for loop for only 500 ms. I came up with the following for loop statement; I was wondering if it is correct.
for(int i = millis(); i >= millis()+500; i++)
{
// time sensitive stuff
}
Thanks
Hello,
I need to run a for loop for only 500 ms. I came up with the following for loop statement; I was wondering if it is correct.
for(int i = millis(); i >= millis()+500; i++)
{
// time sensitive stuff
}
Thanks
I was wondering if it is correct.
No. The middle portion of the for statement is a while clause - execute the body of the statement while the clause is true. In your case, i will not be greater than or equal millis() + 500, so the body will never execute.
A while statement seems more appropriate for what you want to do.
Hi Paul,
what I meant doing was this.
for(int i = millis(); i <= millis()+500; i++)
{
// time sensitive stuff
}
Sorry for the typo
Like Paul says a while loop is what you want.
unsigned long loopDuration = 500;
unsigned long loopStartTime = millis();
while (millis() - loopStartTime < loopDuration)
{
.... do loopy stuff
}
You do have to watch that this is no guarantee that the loop will only execute for 500 millis precisely. It will always loop for 500 millis but could go longer depending on what you do in there. Obviously if one instruction is delay(50000) the loop will run longer than 500 millis.
The problem with the for loop is that in your example i is incremented each time through the loop and has no real relationship to millis. Your loop will never exit unless it takes less than one milli second to execute the loop.