I am trying to do a clock on Atmega8. I have 8Mhz quartz.
I use timer0 interrupt for clock timeticks:
/* Settings */
#define TMR_RELOAD 80 - 5 /* 8 kHz / 80 = 100 Hz */
#define TMR_CNT_MAX 100 /* 1Hz internal counter */
/* internal variables */
static uint8_t tmr_cnt;
inline void TMR0_Init()
{
/* set clock source f_t0 = 8МHz/1024 = 8 kHz */
TCCR0 = _BV(CS00) | _BV(CS02);
TIMSK |= _BV(TOIE0); /* Enable TMR0 interrupt on overflow*/
}
ISR (TIMER0_OVF_vect)
{
if (tmr_cnt == 0)
Clock_Tick1s();
tmr_cnt++;
if (tmr_cnt >= TMR_CNT_MAX)
tmr_cnt = 0;
TCNT0 -= TMR_RELOAD;
}
The problem is that my clock a running too fast or too slow.
Calculated value that I put in TCNT0 register is 80, but in this case the clock is running too slow. When I use 80-4 the clock is also running too slow. When I use 80-5, it's too fast.
I don't know, how it could be???
UPDATE: Now settings are the following, but problem still exists.
/* Settings */
#define TMR_RELOAD 125 /* 31.25 kHz / 125 = 250 Hz */
#define TMR_CNT_MAX 250 /* 1Hz internal counter */
inline void TMR0_Init()
{
/* set clock source f_t0 = 8МHz/256 = 31.25 kHz */
TCCR0 = _BV(CS02);
TIMSK |= _BV(TOIE0); /* Enable TMR0 interrupt on overflow*/
}
ISR (TIMER0_OVF_vect)
{
TCNT0 -= TMR_RELOAD;
if (tmr_cnt == 0)
Clock_Tick1s();
tmr_cnt++;
if (tmr_cnt >= TMR_CNT_MAX)
tmr_cnt = 0;
}