I'm trying to write a while loop that will break out of the loop after a certain amount of time using the millis() function. This is a simplified version of what I'm doing, which does't seem to work:
// include the library code:
#include <Wire.h>
unsigned long sec = 0;
unsigned long timeout = 4000;
void setup() {
Serial.begin(9600);
}
void loop() {
do
{
Serial.println( millis() );
sec = millis();
}
while ( sec < timeout );
}
Looking at the serial monitor, 'sec' happily goes over 4000 without the loop stopping.
Hi Mark, thanks for the reply. I see what you mean and that is clearly an issue with this simple example. However in my actual program the loop is proceeded by more code which should be executed when the loop exits, which it doesn't.
Anyway I've changed the example as you say and now strangely I don't get anything at all printed in the monitor:
Hi Ken, miclevel is essentially a microphone attached to an analogue input. This is being read in the loop - if/when the level of the input exceeds SoundThresh the loop will finish. If miclevel does not exceed SoundThresh within 2 seconds then the loop should also finish (but it doesn't).
if/when the level of the input exceeds SoundThresh the loop will finish. If miclevel does not exceed SoundThresh within 2 seconds then the loop should also finish (but it doesn't).
long constants should be marked long so the compiler knows their type:
do { ... }
while ( (miclevel < SoundThresh) || ( micros()-Start > 2000000ul) );
Also its not obvious but important that the time test is done exactly this way:
Subtract two timestamps from each other (they must either both be from micros()
or both from millis() originally. Compare the difference to a time interval.
Don't compare a timestamp directly to another timestamp, it doesn't work
at wrap-around (which is quite frequent when using micros()). Subtraction
works correctly at wrap-around so long as the result is in range of representation.