Skip to main content
RrW1
Associate III
December 4, 2020
Solved

Question about DWT on STM32L431

  • December 4, 2020
  • 5 replies
  • 2238 views

I have a straightforward question regarding the DWT counter. I am using the DWT->CYCCNT counter to count clock cycle differences in the STM32L431CC, and I noticed that CYCCNT is 32-bits wide. If I were to use HSI16 as my internal clock source, the CYCCNT would still go up to the maximum value of a uint32_t which is 4294967295, and not 16000000 based on my HSI16 clock source right?

Thanks!

timestamp_1 = DWT->CYCCNT;
DoSomeTask();
timestamp_2 = DWT->CYCCNT;
 
if(timestamp_2 < timestamp_1)
{
 /* I originally filled 16000000 instead of MAX_INT here */
 timedifference = timestamp_2 + MAX_INT - timestamp_1;
}
else
{
 timedifference = timestamp_2 - timestamp_1;
}

This topic has been closed for replies.
Best answer by TDK

Correct.

Also, because it's 32-bits, you don't need to do any fancy logic based on if the new value is less than the old one. The overflow will get this correct.

uint32_t timestamp_1 = DWT->CYCCNT;
DoSomeTask();
uint32_t timestamp_2 = DWT->CYCCNT;
 
uint32_t duration_ticks = timestamp_2 - timestamp_1;

 Your code as written will be off by 1 in the case that timestamp_2 < timestamp_1.

5 replies

TDK
TDKBest answer
December 4, 2020

Correct.

Also, because it's 32-bits, you don't need to do any fancy logic based on if the new value is less than the old one. The overflow will get this correct.

uint32_t timestamp_1 = DWT->CYCCNT;
DoSomeTask();
uint32_t timestamp_2 = DWT->CYCCNT;
 
uint32_t duration_ticks = timestamp_2 - timestamp_1;

 Your code as written will be off by 1 in the case that timestamp_2 < timestamp_1.

"If you feel a post has answered your question, please click ""Accept as Solution""."
RrW1
RrW1Author
Associate III
December 4, 2020

Thanks for the answer TDK! I was not aware of that last part though, thanks for adding that to your answer too.