I wrote a program myself to implement the millis() and delay() function without the arduino library. I included a counting variable which counts every second and send its value every second via serial port. What I found is its value runs away from the true value by almost 2 seconds every 3 minutes. Is there anything wrong with my code? Or is that Serial.print() the culprit which may lag that routine? How much time does that Serial.print() takes to execute?
Here is the code:
Edit: I edited the code like this, but the count on the arduino still lag around 4seconds after 4 minutes. It lags 13 seconds after 10 minutes ie, it counts only 587 seconds after actual 600 seconds.
Edit 2: Here is my updated code. Still there is lag in the timing. I get a lag of around 6 seconds in 5 minutes.
#include "Arduino.h"
#include <avr/io.h>
#include <avr/interrupt.h>
void toggle_led(void);
unsigned long volatile millis_count = 0;
volatile char state = 1;
unsigned long volatile current_count = 0;
unsigned int volatile count = 0;
ISR(TIMER0_COMPA_vect) { //Timer interrupt ISR
millis_count++;
if (millis_count - current_count == 1000) {
current_count = millis_count;
toggle_led();
Serial.println(count++);
}
}
int main(void) {
init();
TCCR0B = 0b11; //Timer settings for interrupt at every millisecond
OCR0A = 249;
TIMSK0 |= 0b10;
sei();
Serial.begin(9600);
DDRB |= 1<<5;
for (;;) {
}
}
void toggle_led(void) {
PORTB ^= (1<<5);
}