1

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() 
{
}

enter image description here

2

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 Jun 9 '18 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.