5

I am writing a timer function that uses the micros() function which generates a unsigned long value. To compensate for a roll over condition, I would like to use the maximum value for that variable type. I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that. Still poking around.

3 Answers 3

9

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want. For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.

/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.

Note, arithmetic done in a form like

timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.

4

You don't need "to compensate for a roll over condition".

See my answer: https://arduino.stackexchange.com/a/33577/10794


in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:

maximum unsigned long in c++

You will find the first link leads to:

http://www.cplusplus.com/reference/climits/

In that it says:

ULONG_MAX   Maximum value for an object of type unsigned long int
3

Did you try to do this?:

unsigned long maxUnsignedLong = 0UL - 1UL;

or:

const unsigned long ULONG_MAX = 0UL - 1UL;

Not the answer you're looking for? Browse other questions tagged or ask your own question.