I want to create a real-time clock using ATmega328p microcontroller. The microcontroller's frequency is 1 MHz. So, I think I should use timer interrupts in CTC mode to generate interrupt every second. I have calculated the value for timer CTC mode:
`n = t * f - 1
n
- number of cycles for CTC mode.t
- target time.f
- frequency.- 1
because it takes one cycle to reset the counter.
I set the frequency divider by 64 for the timer.
n = 1 s * (10^6 Hz / 64) - 1
n = 1 s * 15625 Hz - 1
n = 15625 - 1
n = 15624
So, I have code:
#include <avr/interrupt.h>
#include <util/delay.h>
#include <time.h>
static unsigned long t = 0;
ISR(TIMER1_COMPA_vect) {
t++;
}
static void InitializeTimer() {
cli();
OCR1A = 15624;
TCCR1B = (1 << WGM12) | (1 << CS10) | (1 << CS11);
TIMSK1 = (1 << OCIE1A);
sei();
}
[[noreturn]] int main() {
InitializeTimer();
LCD_SetUp(PC_5, PC_4, PC_3, PD_0, PD_1, PD_2, PD_3, PD_4, PD_5, PD_6, PD_7);
LCD_Init(2, 16);
while(true) {
tm* time = gmtime((time_t*)&t);
LCD_Clear();
LCD_Printf("Time: %02d:%02d:%02d", time->tm_hour, time->tm_min, time->tm_sec);
_delay_ms(100);
}
}
This code prints number of seconds since the start of the microcontroller to an LCD display. It really does, but since even 3 minutes time error is 2 seconds, since 10 minutes time error is 5 seconds, since 45 minutes time error is 30 seconds. I checked the time error using my phone's stopwatch. Why there is a time error? Error during calculation? What are the reasons for this? Thanks in advance!