The number 100 is just something I am using as a place holder. I dont even know if the above code would work. I need the value animal to change every 25 seconds. I cant hold the whole code up with a delay. Thanks for any help.
unsigned long time; // current time
unsigned long oldtime = 0; // pevious time
void setup()
{
}
void loop()
{
time = millis(); // stores clock cycles to time
if (time >= (oldtime + 25000)) // if 25 seconds or more has passed
{
// change value
// stores the current time to the old time to be ready for the
// next time comparison.
oldtime = time;
}
}
if (time >= (oldtime + 25000)) // if 25 seconds or more has passed
Due to the fact that time and oldtime can overflow, addition is generally not recommended. The same effect can be achieved using:
if (time - oldtime >= 25000) // if 25 seconds or more has passed
If time overflows, there is a flag set. Same holds true if/when oldtime overflows. On subtraction, the overflow flags are checked, and the result is corrected for overflow conditions.
The overflow flags are not checked the same way when addition is used, so oldtime + 25000 could overflow, resulting in a small number. The next comparison, after oldtime is set, will result in millis() returning a very large value, which is larger than the small value returned when oldtime + 25000 is computed, resulting in a pass through the loop after only a few milliseconds.
On subtraction, the overflow flags are checked, and the result is corrected for overflow conditions.
I really don't like this phrase. I'd say so: when millis overflows, the subtraction overflows too and it happens that the result of subtraction is correct under all circumstances (unless the actual time interval is really veery large, more than about 70 days). Here, "correct" means that it does what it is intended to - calculates the time difference - despite overflows.
Why I do not want to talk about overflow flags is because subtracting longs needs several byte arithmetic operations, involving all the overflows that happen in most of them. Thanks to the compiler 8-), we do not need to know how it is actually done, and we simply enjoy long integer operations.
And, oldtime is just a variable, and all the overflow flags that were set during it's calculation are already overwritten by other arithmetic performed since it was computed. (I really do not think that overflow flags are implicitly stored somewhere, for every variable...)
Well, I completely agree that (time - oldtime >= 25000) is overflow-resistant while (time >= (oldtime + 25000)) is not, I just don't like the explanation.