Thursday, September 27, 2012

Delay (PIC16F690)

How to kill your micro controller's time.


Today we are going to create subroutines that do nothing more than killing the time of micro controller. These subroutines will be used almost to any serious application we are going to make. In order to create precise delay functions we have to know the frequency of the micro controller crystal, and how many cycles ( A 'cycle' is the smallest amount of time it takes for your micro controller to do anything) will take for every command to be executed.
I think an example will clear it all out. Let assumed that our micro controller clock is set to 4 MHz, and we would like to make a delay of 100 uS.

  1.  ;***** VARIABLE DEFINITIONS (examples) 
  2. #define COUNTER_us 0x20
  3. .... 
  4. ;somewhere in the program
  5. call Delay100us
  6. ......
  7. ......
  8. Delay100us
  9. movlw d'31'
  10. movwf COUNTER_us
  11. delay100us
  12. decfsz COUNTER_us, 1
  13. goto delay100us
  14. nop
  15. nop
  16. return
Lets start by the variable definition, this is not necessary, but is very helpful. So we are defining a variable with name COUNTER_us which is at the 0x20 cell of memory and its going to be used as a temporary register which is going to help us to count the time. When the programmer uses the call command it means from that moment the delay should be start counting, so the total instructions are given below:

Instructions = 2(call) + 1 (movlw) + 1 (movwf) + 30x[1+2](decfsz and goto) + 2(decfsz the last time) + 2 (2 nop) + 2 (return) => Instructions = 100

You have to remember that every instruction cycle = 4 Tosc (Tosc = 1/frequency of the pic). So lets do the maths:
Tosc=1/Fosc = 1/4MHz = 0.25uS
100 instruction cycles = 4x0.25us =>uS = 100/(4x0.25) => Time = 100uS

And now you can create more delay subroutines, based on that logic. For example if you want a delay of 1ms you can use this delay 10 times, and so on.

Please keep in mind that post because we are going to use delay functions to a lot articles.

More about delay functions you can find here:
http://pcbheaven.com/picpages/Instruction_Cycle_Duration_and_Programmable_Delays/
http://www.piclist.com/techref/piclist/codegen/delay.htm (i tried this and is very good)
http://waihung.net/microchip-delay-calculator/ ( i didn't tried it)


No comments:

Post a Comment