timer.read() is a negative number

31 Jul 2010

#include "mbed.h"

extern "C" void mbed_reset();

Timer timer;

int main() {
    int t=0;
    timer.start();
    printf("Begin...\r\n");
    while(1){
        t=timer.read();
        printf("t = %d \r\n", t);
        if(t>3600){ //-------------------------------------- can't execute
            printf("mbed_reset \r\n");
            mbed_reset();
        }
        wait(5);
    }
}

 

When timer.read()>2147,it changes to negative number(-2146).

Why? Please tell me!

Thanks!

zhenjiang

31 Jul 2010

Hi Zhenjiang,

The behaviour you are seeing is simply overflow of the counter. The timer uses an internal tick of 1us, and is really designed for timing small delays of the order of fractions of a second. See:

The longest time you can actually time is approx 2^31 us, which as you show is about 2147 seconds.

If you are trying to time dleays more like minutes than milliseconds, you may be better off using the real time clock:

Hope that helps!

Simon

21 Mar 2011

I guess the solution might involve taking control of one of the hardware timers directly. In many embedded systems, a free-running unsigned timer is common. It rolls over to zero from max unsigned. Measurements of delta time are then easily performed with a "now" - "previous" subtraction.

As an example, a CAN logger may be time stamping the messages in 1 uSec resolution (it probably doesn't need 1 uSec since a typical 8-byte packet may take 250 uSec at 500k, but 1 mSec is too coarse). As a logger, it wants accurate timestamps for the entire collection of messages. A complex logging function may be to sit and wait for an event, then write the pre-trigger through post-trigger buffer to non-volatile. So, it could easily be that the trigger is near the point where the timer goes negative.

I didn't study it - can this timer be cast to unsigned to get the desired behavior?