Clock with Atmel AVR Mega 8 and a clock crystal


Allready some time ago I tried to build a clock with a AVR Mega 8 and a clock crystal (32,768kHz). But by some reason this clock didn't get precise. The error was about 10min a day, so really huge - and I had no explaination for it. Why was the clock crystal not precise enough?

Now, I found again some time for this small side project - and I tried the following circuit with the clock crystal.

uhrenquarz.jpg
Of course, there was a display too, but I only wanted to show the important part.

But still, even with the changeable capacitor the clock was crazy wrong. There was no chance at all to pull it to the correct frequency. So, I read again the manual of the Mega 8 and this time I found the reason.

The fuse CKOPT was programmed by default, which means that internal capacitors of 36pF are activated. And because of this, the specification of the clock crystal was totally exceeded. Thats why my clock was allways so wrong. Now, its less than a second a day, which is good enough for me.

Important Assemblerparts:

 ldi r16, 0b00000101 ; Prescaler for Timer2 = 128 -> 128*256 = 32768 1 overflow per second
 out tccr2, r16
 ldi r16, 0b01000000; Overflow Interrupt of Timer 2 activated
 out timsk, r16

 

 

TIM2_OVF:
 push r16   ; Working register to stack
 in r16, sreg ; Sreg to stack as CPI instructions will change ist
 push r16     ;

 inc r21 ; increase second
 cpi r21, 60
 brlo nothingtodo 
 clr r21    ; second is 60, clear it and increase minute
 inc r22
 cpi r22, 60
 brlo nothingtodo
 clr r22
 inc r23   ; increase hour
 cpi r23, 24
 brlo nothingtodo
 clr r23 

nothingtodo:

 pop r16         ;
 out sreg, r16  ; restore sreg
 pop r16         ; restore working register

reti

Typical questions to this article:

Why is the clock crystal 32.768kHz not running correct?
How can I make a clock with a Atmel Mega 8 and a clock crystal?
My Clock is running to fast



(c) Schoeppl.info - Last modified: 05.07.2006