I am trying to output something every one second with the following code.
volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
{
Serial.begin(19600);
noInterrupts();
TCCR2A = TCCR2B = 0;
TCNT2 = 0;
OCR2A = 124; //Zero Relative 125
TCCR2B = B00001101; //prescaler = 1024
TIMSK2 |= (1 << OCIE1A);
interrupts();
Serial.print("Begin... \n");
}
//**********************************************************************
// Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
// 16Mhz / 125 / 1024 = 125 Hz 0.008s
ISR(TIMER2_COMPA_vect)
{
timerCounts++;
if (timerCounts == 125){
Serial.print("1s");
timerCounts = 0;
}
} // end of TIMER2_COMPA_vect
void loop()
{
}
In the above code, I have set the OCR2A
(output compare register) to 124``, which is well below 256
(2^8). A user defined counter is also used.
However, when I execute the programme, the interval between consecutive outputs is less than 1 second.
When I change it to timer 1, the interval becomes roughly 1 second. When I change it to timer 0, the interval becomes longer than 1 second.
Anyone knows why?
Thanks.