AnsweredAssumed Answered

Number of clock cycles per instruction

Question asked by colla.ivan on Mar 7, 2016
Latest reply on Mar 8, 2018 by Erwan Y
Good morning to everyone.

I am trying to figure out how to toggle periodically a digital output pin with a given frequency. The system clock is configure the internal oscillator, so it should be 16 MHz.

I set a timer with a prescaler of 101, so, if I understand correctly, it should count 1 every 100 **** tick.

Now, for example, I am trying to toggle a pin evry 20 ms. If I understand correctly, 16 MHz, should be 16000000 clock cycles per second. If I count 1 every 100, the timer should be 160000 every second. 
20 ms is 1/50 seconds, so 1600000/50 = 3200.

In my code, I execute various type of operation in an infinite cycle. When I have to evaluate if 20 ms are passed, I verify the STM counter. If 3200 counts are passed from before, I change the output.
The control implemented is something like this:

               ULONG ulNow = STM.CNT.R;
               ulElapsedTime = ulNow - ulWaveTimer;
               if (ulElapsedTime  >= 3200)
               /* Time passed. Change output and reset timers. */

The fact is that It seems that from one check and the others pass too many clock cycles, so the frequency obtained is not what I desire, but less. 

Is there a more smart way to implement an output that change with a desired frequency?
There is some fixed relation between the C code I write and the number of machine instructions that I obtain after compilation? 

Thank you,
     Ivan


Outcomes