# Generating 1 second with avr and timer 0 for Atmega32A

dears: we have to Generate 1 second with atmega32A and mikrobasic software. so I have configured timer 0 and avr with this way:

const _THRESHOLD = 250
TCCR0=0x04
TCNT0=0x06
OCR0=0x00
' // Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x01


and overflow function:

sub procedure Timer0Overflow_ISR iv IVT_ADDR_TIMER0_OVF
' // Reinitialize Timer 0 value
TCNT0=0x06
if (counter1 >= _THRESHOLD) then
counter1 = 0


so with TCCR0=0x04 WE USE 256 presqale with external clock 16MHz wich :

16MHz/256=62500


which means timer 0 clock is 1/62500=0.000016 Second which TCNT0=0x06 timer 0 over flow clock is 256-6=250 which take 0.000016*250=0.004 Second for one overflow of timer 0 with TCNT0=0x06 .

so for creating 1 second, it needed to count timer0 overflow for 1/0.004=250 turn of timer0 overflow. the above codes are written based of this calcuation. SO when we program this codes into atmega32A, for 5 minutes the clock is Lag for 5 seconds.

Changes based of new comment.

I have changed TCNT0=0x07 for 249 clock of timer0 and 1 clock for overloading ti,er values. but still counter lag for 5 second at 5 minutes .

Thanks a lot.

• What do you mean by creating 1 second? – Long Pham Sep 27 '18 at 9:22
• Uhm, you cannot generate time. What you can generate using an ATMega is a signal that's high for 1 second and then low for 4 seconds. – Bimpelrekkie Sep 27 '18 at 9:35
• @Bimpelrekkie: OP is not stupid. There is obviously a language barrier preventing him from expressing it any better. – Rev1.0 Sep 27 '18 at 9:37
• Read the datasheet carefully. I have seen counters where it requires 1 cycle to re-load the counter thus a limit of 250 is actually 251 clocks. – Oldfart Sep 27 '18 at 9:43
• @LongPham: True, it was just meant to point him into the right direction. And I don't think the 5min/5s is accurate. Its potentially several "1 counter off" things coming together. – Rev1.0 Sep 27 '18 at 9:45

You have timer0 counting every 16 µs, which means that the ISR must update the TCNT0 register within that amount of time in order for your calculations to be correct.
I find myself wondering whether the ISR actually does the write to TCNT0 before it has already incremented several times, which would explain the roughly 1-part-in-60 error that you're seeing.
One experiment would be to see whether you get the correct timing by increasing the TCNT0 value even more. Try setting TCNT0 = 0x0B in your ISR. If this gives you something closer to the correct timing, that means that there's a lag on the order of 64 µs between when the overflow interrupt occurs and when the write to TCNT0 occurs. This would not be unheard of in interpreted code.