cancel
Showing results for 
Search instead for 
Did you mean: 

how to get the right 1us period

mmed
Associate III

Hi everyone,

Please how can i get the right period 1us without using DWT unit,

I want to synchronize with sensor that requires a high precision of clock.

Thanks in advance,

Regards

5 REPLIES 5
Uwe Bonnes
Principal III

For high precision, use timers. You can try to calculate the period for the DWT, inhibt interrupts and busy wait for the calculated timer value, but that will have more jitter and inhibits other urgent tasks.

Use a TIM clocking sub-microsecond and not interrupting ​

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
mmed
Associate III

Hi,

please, is this following code the best way to get 1us ?:

void TIM_INT_Init()

{

TIM_HandleTypeDef htim1;

htim1.Instance = TIM1;

  htim1.Init.Prescaler = xxxxx;

  htim1.Init.Period = xxxxx;

  htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

  htim1.Init.CounterMode = TIM_COUNTERMODE_UP;

  HAL_TIM_Base_Init(&htim1);

 HAL_TIM_Base_Start_IT(&htim1);

}

void microseconds_Delay(int Delay){

 uint32_t initTime = __HAL_TIM_GET_COUNTER(&htim1);

while((__HAL_TIM_GET_COUNTER(&htim1)-initTime) < Delay){

 }

}

If there is no wrong logic in this code, how can i determine Prescaler and Period to get 1us? I work with system clock equal to 168MHz.

Please can anyone help me on this thread and thanks in advance,

TIM1 is 16-bit, you need to use uint16_t for the math to work properly/consistently. Period should be maximal, ie 0xFFFF

For 1-us (1 MHz) Prescaler = 168-1; // DIV168

For short delays I'd set Prescaler = 0; // DIV1 and multiple the Delay by 168 to count ticks of the finer precision clock.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

Many thanks CLive and Bonnes for your support.

Please if i can check again about TIM1 configuration: the following example is enough then to get 1us (and obviously multiple of 1us). I would check if there is wrong instruction or i miss any configuration in the two functions void TIM_INT_Init() and void microseconds_Delay(int Delay)

void TIM_INT_Init()

{

TIM_HandleTypeDef htim1;

htim1.Instance = TIM1;

  htim1.Init.Prescaler = 0x00A7; // ==>167

  htim1.Init.Period = 0x0; // ==> 0

  htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;

  htim1.Init.CounterMode = TIM_COUNTERMODE_UP;

  HAL_TIM_Base_Init(&htim1);

 HAL_TIM_Base_Start_IT(&htim1);

}

void microseconds_Delay(int Delay)

{

 uint32_t initTime = __HAL_TIM_GET_COUNTER(&htim1);

while((__HAL_TIM_GET_COUNTER(&htim1)-initTime) < Delay)

{

 }

}

I am very thankful for your help .

Have a nice day