Advertisement
kyos

Timer Delay

Aug 23rd, 2016
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1.  * Created: 2016/08/22 04:02:04 PM
  2.  *  Author: Kai
  3.  This code is written in order to set up a manual delay function using the 16 bit counter TCNT1
  4.  and its control registers TCCR1A and TCCR1B which is set accordingly to make the counter run in normal mode
  5.  and count for 4 seconds.
  6.  the bit 0x01 in the TIFR1 register is also used to indicate when the timer has reached overflow
  7.  */
  8.  
  9.  
  10. #include <avr/io.h>
  11. #define F_CPU 16000000UL
  12. #include <util/delay.h>
  13.  
  14. void to_delay (void);
  15.  
  16. int main(void)
  17. {
  18.     DDRB=0xff;      // outputs
  19.    
  20.     while(1)
  21.     {
  22.         PORTB = 0x20;       // sets pin 13 high
  23.         to_delay();         // calls a function which manually delays the code by 4 seconds
  24.         PORTB = 0x00;       // sets pin 13 low
  25.         to_delay();         // again, calls the same function which manually delays the code by 4 seconds
  26.     }
  27. }
  28.  
  29. void to_delay (void){
  30.     TCNT1 = 3026;           // presets the 16 bit counter to the decimal value of 3026 / 65536
  31.     TCCR1A = 0;             // sets the control register to normal mode
  32.     TCCR1B = 5;             // sets the prescale factor to 1024. This devides the clock input by 1024. this also starts the count
  33.     while((TIFR1&0x01)==0); // holds this line of code until the counter reaches overflow
  34.     TCNT1 = 0;              // clears the counter
  35.     TIFR1 = 0x01;           // resets the flag bit in the TIFRn register. this is done by SETTING the TOVn bit
  36.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement