cancel
Showing results for 
Search instead for 
Did you mean: 

Hardware Timer usage to get the time elapsed

SJant.1
Associate III

Hi STM Community,

I have just started to work on the STM32L4S5 based microcontroller and I wanted to use Hardware timer to get the time elapsed between two instructions, I generated a code using STM32CubeMX for Timer3 but it gave me only the initialization of the timer3.

How can I use the HAL driver to obtain the time elapsed? I have created timer in Base mode and the Period is 65535. I mean will it upcount till this Period and give an event for me to know? if so how do I capture the event?

If there is any example program available, sharing it to me would be really helpful.

Thanks a lot!!

5 REPLIES 5

Hello

Use the timer , preferably TIM2(32bit counter) in free runing mode at max freq. and take snapshots of counter before and after the instruction.

HAL functions add a lot of overhead to measurements

Suggest use      DWT->CYCCNT counter that runs continously

unsigned long cycles;

DWT->CYCCNT=0;

 //function under examination

 cyccles = DWT->CYCCNT;// result in clock cycles (plus one cycle )

SJant.1
Associate III

Hi Vangelis,

Thanks for your response.

H​ow can this clock cycle be scaled to time?

I mean each clock cycle can be treated equal to 1sec or something like that for so and so frequency?

Is there any document to which I can refer?

Actually I want to get the time elapsed in nano seconds so wanted to see if I can scale a clock cycle to a particular time.

Thanks

Hello

The frequency of the counter is the HCLK freq. = sysclck/ AHB divider = core clock freq. This counter counts cycles of core clock.

DWT Data Watchpoint and Trace registers are part of technical refernce manual for Cortex . (This is for M4)

Detailed explanations will find here. (for M3)

>>Actually I want to get the time elapsed in nano seconds

The max resolution for a 120 MHZ clock is 8.33 nanoseconds. (11/120MHZ)

Hi Vangelis,

I wanted to know more abt using the timer 3 instead of DWT. Actually the DWT point was very helpful.

But I want to validate a hardware timer on my board using the HAL drivers. So as you mentioned in the first part of your answer and I quote,

"Use the timer , preferably TIM2(32bit counter) in free runing mode at max freq. and take snapshots of counter before and after the instruction.

HAL functions add a lot of overhead to measurements"

Can you please describe what you mean by take snapshots of counter before and after the instruction, can you please elaborate on how to do this?

Should I read a register? if yes which one?

Or is there a HAL function to do this?

Please help me with the info.

Thanks a lot for your time!!

Piranha
Chief II

> Is there any document to which I can refer?

Timers and other peripherals are explained and documented in the respective MCU reference manual. And additionally one can read AN4776.