Difference of two integers gives randomly a large result

Hi, sadly I can't show the serial prints I'm getting to explain my problem visually, because I won't have access to my Arduino until Monday, but I'll do my best with words:

For a university project, I wrote a code that keeps track of the time (using millis() function), and once the difference between the reference time (the time at which the program starts its cycle) and the current time exceeds a certain threshold (we use a range from 1.5 to 5 seconds), it deactivates the program, until we trigger it again. This allows us to measure over a closed interval of time, without a new result appearing on the screen over and over again.

However, at some (random?) point, this part of the code

if((millis()-reference)>=off_time){
    //Serial.print(millis()-reference);
    freq();
    deactivate();
  }

starts to spit out the measured frequencies with almost no interval between. To test what caused this, I added that Serial.print part and it appears that at some point the difference

millis()-reference

becomes very large (jumps to a value around hundreds of thousands), and therefore is constantly larger than the off_time (which is around 1500-5000). Sidenote: reference too is defined as an integer, so I doubt the problem is in the definition of the values.

Any ideas why this might happen?

Reference needs to be an “unsigned long”

reference and off_time should be defined as unsigned long.

Also, if your deactivate() function doesn't reset reference then the value will be printed over and over again.

why would that matter? and if it does, why would it work fine for the initial 20 seconds or so?

that's true, it doesn't, because the activate() function does that instead, which runs before the counter loop can be started;
and i mean, it works fine for the first ~20 seconds or so, but breaks down later
thanks for the suggestion though!

Maybe 32.768 seconds later, when the 16 bit int overflows.

for some reason i thought regular integers were 32-bit |:
this is probably the issue, thank you

They may be, depending what model of Arduino you are using (you forgot to say).

See what the man page has to say

It depends on the hardware platform. That is why using int may result in a different size integer for different processors. This is one reason the following typedefs are provided so that the definitions are unambiguous:

uint8_t
uint16_t
uint32_t
uint64_t
int8_t
int16_t
int32_t
int64_t

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.