First time post here migrating from the Arduino forums (be gentle!).
I'm building an alarm clock using the ATMEGA328P running at 8MHz internal clock at 3.3V, using Timer2 with a 32.768kHz watch crystal. Schematic and details here.
I'm scratching my head because my clock is almost exactly running at half speed.
I'm following AN 1219 which uses the following logic:
32.768 kHz = 2^15 Hz
/128 prescaler = 2^7
this gives 2^8 = 256 Hz, so an overflow should occur every 1s.
Here is the code snippet for setting everything up (full code is here):
ASSR |= (1<<AS2); //set Timer/counter2 to be asynchronous from the CPU clock TCNT2 = 0; // reset Timer/counter2 TCCR2B = (1<<CS00)|(1<<CS02); //Prescale the timer to be clock source/128 while (ASSR & ((1<<TCN2UB)|(1<<OCR2AUB)|(1<<TCR2AUB))); //Wait until TC2 is updated TIMSK2 |= (1<<TOIE2); // enable overflow interrupt sei(); // enable interrupts
I then use ISR(TIMER2_OVF_vect) as per the application note (increment seconds).
Possible explanations I have tried to rule out:
- Vcc of 3.3V is an issue (datasheet gives me 0 - 10MHz@2.7 - 5.5.V)
- Load capacitance issue of crystal - it has 6pF load capacitance so as per datasheet doesn't need extra capacitors. Also it's almost exactly 2x slow so binary issue IMO
- I've messed up the registers (most likely explanation)
Any help much appreciated,