cancel
Showing results for 
Search instead for 
Did you mean: 

The clocks each command takes

Arman Ilmak
Senior
Posted on April 27, 2018 at 19:51

Hi.

I wanted to know that for example how many clocks a while loop takes.

Do you have any ideas or any articles on this matter?

Note: this post was migrated and contained many threaded conversations, some content may be missing.
21 REPLIES 21
Posted on May 05, 2018 at 15:10

1. have a free-running clock;

2. time stamp your execution for delays.

something like this would work:

//get time stamp

&sharpdefine tick_get()  (TIM2->CNT)  //TIM2 initialized as a free running clock

//delay a number of cycles

void delay(uint16_t cnt) {

  uint16_t start_time = tick_get(); //time stamp the start of the routine

  while (tick_get() - start_time < cnt) continue; //wait until the desired number of cycles has passed

}

when you want to delay a certain amount of us, or ms, just feed it with the right number of cycles.

the code above is blocking. a non-blocking version would be something like this:

//test if a number of cycles has passed

char isdelay(uint16_t cnt) {

  static uint16_t start_time = 0; //time stamp the previous start of the routine

  if (tick_get() - start_time < cnt) return 0; //the number of cycles specified has not passed

  start_time += cnt;  //increment start_time

  return 1;  //indicating that the set number of cycles has passed

}

Posted on May 10, 2018 at 12:43

Thanks. Does it work with 8-bit MCUs that the maximum clock is 16 MHZ?

Something that I used was this:

void delay_us(unsigned int d)

{

TIM5->CNT=0;

while(TIM5->CNT<d);

}

And TIM5->CNT counts every 1us(TIM5 clock is 1MHz).

This works when the CPU clock is 120 MHz(When I'musing my stm32f217 MCU).

But when I use the same settings with 16MHz CPU clock this does not work(i tried this in both stm32f217 and stm8s that I have).