void timer1CTC_Init ( int max_count , int my_div) {
TCCR1A = 0 ; // c l e a r a l l b i t s
TCCR1B = 0 ; // c l e a r a l l b i t s
OCR1A = max_count - 1 ; // maximum count - 1
TCNT1 = 0x0 ; // r e s e t counter
TIFR1 = 0x7 ; // c l e a r a l l i n t e r r u p t f l a g s
TIMSK1 = 0 ; // d i s a b l e a l l i n t e r r u p t s c a l l to MCU
TCCR1B |= 0x8 ; // s e t WGM12 to 1 , mode 4 CTC
if (my_div == 1) {
TCCR1B |= 0x01 ; // s e t CS to dividy clk by 1
} else if (my_div == 8) {
TCCR1B |= 0x02 ; // s e t CS to dividy clk by 8
} else if (my_div == 64) {
TCCR1B |= 0x03 ; // s e t CS to dividy clk by 64
} else if (my_div == 256) {
TCCR1B |= 0x04 ; // s e t CS to dividy clk by 256
} else if (my_div == 1024) {
TCCR1B |= 0x05 ; // s e t CS to dividy clk by 1024
}
}
void setup ( ) {
DDRB = 0xF0 ; // s e t PB7: 4 to output
PORTB &= 0x0F ; // c l e a r PB7: 4
// s e t timer 1 count frequency to 2 Hz ( 0 . 5 second )
// by counting 31250 times at 62500 Hz (16 MHz divided by 256)
timer1CTC_Init (31250 , 256);
}
void loop ( ) {
if (TIFR1 & 0x2 ) { // check OCR1A match i n t e r r u p
TIFR1 = 0x2 ; // c l e a r OCF1A match i n t e r r u p t f l a g
PORTB ^= 0x80 ; // t o g g l e PB7
}
}