I set up some code to count seconds using timer2 on an ATMega168(i would have used timer 1/0 but they don't wake up the avr in sleep mode apparently).
I'm running off a 4Mhz crystal and i thought that i could conveniently do:
1. Prescale by 256
2. CTC on 125
3. Second counter increments up to 125
4. Second counter clears and seconds increment, etc
So, i wrote up the register code and this is what i came up with. As a result (trying a basic count down timer using these settings), the seconds rack up about 200 times faster than they should do. Doing the maths, around 200 per second at 125*125 gets near on 4Mhz anyway, let alone a prescaler!
void timer2_init(void) { ASSR |= (1 << AS2); //Set timer 2 to CTC mode TCCR2A |= (1 << WGM21); //Set the timer 2 compare value (A) to interrupt every 125 ticks OCR2A = 125; //Set clock frequency to external crystal, prescaled to 256 TCCR2B |= (1 << CS22) | (1 << CS21); //Set the interrupts to enable on match TIMSK2 |= (1 << OCIE2A); } ISR(TIMER2_COMPA_vect) { //1/125 milliseconds millisecond_counter++; //Run every second if(millisecond_counter == 125) { millisecond_counter = 0; //run some code, update some variables, etc } }
I was basing this from a combination of the newbie guide to timers and this implementation of a RTC:
http://www.shapeshifter.se/2009/...
I set the AS2 bit to clock from the crystal on TOSC1 (as if i were using a watch crystal, but a lot faster) so in theory this should work.
How does this work if my CPU frequency is also clocking from the crystal? I've managed to get it to get a rough second timer by putting in a 1024 prescaler and having the second counter to go up to around 5000 but something is going wrong somewhere because that would imply it's clocking much faster than the CPU which is - obviously - impossible.