Email: Password: Remember Me | Create Account (Free)

Back to Subject List

Old thread has been locked -- no new posts accepted in this thread
???
03/03/10 09:53
Read: times


 
#173771 - Using a timer in C
Responding to: ???'s previous message
Christoph Franck said:
C gives no guarantees on how exactly created assembly will do what the source code states. Theoretically, the compiler could insert random NOPs in the code if it feels like it. If you need cycle-exact delays, assembly is the way to go.

If you demands aren't that strict, using a timer (or other otherwise unused peripheral that can measure time) should work. This can be done in C.


Expanding on this. Fixed delays that are known at compile time can be handled by a C macro.

You can calculate the # timer ticks as the (CLOCK_FREQUENCY/ANY_PRESCALER/1000000)*microsecs. Set the timer so that it will overflow after these ticks. Wait for the overflow flag to be set.

Obviously Compilers may use different assembly instructions to write immediate values to 8 bit registers. So you cannot guarantee that it uses "MOV TL2,#250" or "MOV A,#250 with a MOV TL2,A" or even if the Compiler 'knows' that a register already holds a certain value.

So you have a certain amount of unpredictable overhead that you may or may not want to account for in the tick calculation. For delays involving high #'s of clock cycles this overhead becomes insignificant.

So the simple answer is NO for an accurate C delay even with a timer.
If you can accept possible differences of a few cycles between Compilers then you will be fine.

David.

List of 9 messages in thread
TopicAuthorDate
fixed length delays in C            01/01/70 00:00      
   Can't do it without assembly.            01/01/70 00:00      
      HLL gives no guarantees            01/01/70 00:00      
      Using a timer in C            01/01/70 00:00      
         overheads            01/01/70 00:00      
            Use a dedicated timer            01/01/70 00:00      
               non-functional code            01/01/70 00:00      
                  Interrupts aren't the biggest problem ...            01/01/70 00:00      
   break apart            01/01/70 00:00      

Back to Subject List