Best method of timing?

I'm trying to think up the best method of internally timing something

There are for loops, while loops, which timing can change depending on what's happening within then

Delays, which are not good and will just lock up the system which I can't afford.

Could someone please prescribe an easily implementable method of creating timing methods for 0.1 - 2 seconds?

Blink without delay.

Cheers Coding :slight_smile:

Minor query. Is the the variable large enough so that the millis() function counter will never exceed it? Otherwise long term that could lead to some strange happenings.

unsigned long is 4 byte right? so 2^(8*4) = max value before overflow
if u have to do something precisely with microsec error you can use interrupt, like timer interrupt or similar.
an interrupt will stop your code and execute interrupt code, so don't make big thing inside it or the interrupt will recursively call itself until the stack is full and arduino crash :-d
sorry for bed english :wink:

Minor query. Is the the variable large enough so that the millis() function counter will never exceed it? Otherwise long term that could lead to some strange happenings.

The millis() function returns an unsigned long. That will rollover after approximately 49 days. But, so what?

As long as you do not do addition with unsigned long types, like adding an interval to define when to stop doing doing something, and instead use only subtraction, like subtract when that something started from now and test the result against the interval, you will not have any issues if/when millis() rolls over.

Given the code example from the blink without delay tutorial:

if(currentMillis - previousMillis > interval)

previousMillis = currentMillis;

Won't currentMillis rollover, hit 0 and start counting again and previousMillis will be a high value causing currentMillis - previousMillis to be a large negative value screwing up the if test?

Won't currentMillis rollover, hit 0 and start counting again and previousMillis will be a high value causing currentMillis - previousMillis to be a large negative value screwing up the if test?

No it's been explained in the past, posted somewhere around here. From memory, the first subtract on rollover will generate a carry bit so not causing a negative results and on the next loop everything will be happy ever after. Maybe I don't recall the explanation just right. ;D

But it does work, roll-is no problem if subtraction is used as shown.

Lefty

Sweet, better safe than sorry :smiley: