11 years, 6 months ago.

Bug or misunderstanding? Using Timer?

I understand the the Timer object uses only one timer. However I've experienced some odd behavior when the object is created in multiple places.

void function_parent()
{
   Timer t;
   t.start();
   ...
   function_child();
   t.reset();
   // do something that we know how long it takes
   t.read(); // expected value
}

void function_child()
{
   Timer t;
   t.reset();
   // do something that we know how long it takes
   t.read(); // not the expected value
}

The problem I'm having is in the child function. I'm sure if I could see the source code inside of Timer I would better understand why this is causing problems. Obviously I could just pass a pointer to the timer object, but I don't understand why the above code doesn't work.

3 Answers

11 years, 6 months ago.

All mbed timing functions use indeed one timer (probably you are right it is timer 3). However there is a software layer between the physical timer, and the timer function you create: each timer you create acts completely independent. Thats why you can create 20 timers and 10 tickers at the same time, which all run on the same hardware timer but act independently. While it costs a little bit of performance, it gives you huge flexibility (which I realised especially after doing for the first time something with Arduino, the mbed timing functions are so incredibly handy).

Now of course I also dont have access to the source code, but simplified it will probably when you call the start function store the current value of timer3 in a variable. Then when you read it, it simply substracts current timer value, from the previously saved value.

TL;DR: Each timer object is independent from the others. They do run on the same hardware timer, but as user you dont notice that.

Accepted Answer
11 years, 6 months ago.

The Timer does not have a 'restart()' method as far as I know. It doesnt show in the documentation. The documented methods are start() and reset().

You propably use reset() where it says restart() in your code. The problem then is that your Timer t inside child is not actually running since the t.start() has not been called. The following code should work as expected.

void function_child()
{
   Timer t;
   t.start();
   t.reset();
   // do something that we know how long it takes
   t.read(); // Now it should be the expected value
}

Note that this is a new Timer, locally declared and independent from the Timer in the parent. This local Timer will be destroyed when you exit the child function.

11 years, 6 months ago.

I tried that, and unless I'm mistaken the Timer object uses timer 3 and if you start it in one place it should continue running and creating another object just creates another API reference to timer 3?