I must be overwrought or something... I just can't get the calculation of the timer frequency right. I have a 16 MHz crystal on the Atmega328. I want 1 kHz timer interrupt rate. So I chose prescaler = 64 and counter top = 249, that is
fTimer = fCPU/prescaler/(top+1) = 16 MHz/64/250 = 1 kHz
But my oscilloscope shows 2 kHz... !? Why?
I have read Timer2 Compare Interrupt not working as expected but the accepted answer doesn't make it better. There the frequency is half as high whereas mine is twice as high as expected.
Code:
const int signalLED = 1; //14;
void setup()
{
pinMode(signalLED, OUTPUT);
digitalWrite(signalLED, LOW);
TCCR2A = 0; // set TCCR2A register to 0
TCCR2B = 0; // set TCCR2B register to 0
TCNT2 = 0; // reset counter
OCR2A = 249; // top value in CTC mode
TCCR2A |= (1 << WGM21); // enable timer2 CTC mode
TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
TIMSK2 |= (1 << OCIE2A); // enable timer2 compare interrupt
sei(); // allow interrupts
}
ISR(TIMER2_COMPA_vect)
{
// generate peak
digitalWrite(signalLED, HIGH);
digitalWrite(signalLED, LOW);
}
void loop()
{
}
1 Answer 1
Your comment:
TCCR2B |= (1 << CS21) | (1 << CS20); // 1:64 prescaling for timer 2
doesn't match the actual setting (= 1/32)
Also there are some issues with setting Timer2 CTC mode, it's better to set mode, then OCR2A + TCNT2 + interrupts and then Prescaler to start the timer. It behaves as there is OCR2A=0, so the frequency is much higher than expected.
-
That was the problem. I just mixed up the prescaler setting specs of Timer1 with those of Timer2. For Timer1 CS11|CS10 is 64. I knew that standing up too early wouldn't be good for me... ;-)oliver– oliver06/09/2018 05:49:03Commented Jun 9, 2018 at 5:49