Problem with AtMega2560 timers.

I'm using timer 5 on my Arduino Mega 2560 board to call an interrupt with a certain interval.

The timer is in CTC mode, so it should reset after timer counter reaches specified number.

The problem is that at first timer works fine, but after timer triggers, it begins rapidly calling interrupt each tick, instead of resetting.

Things i tried:

  • Tried using other timers - same thing
  • Tried setting timer counter back to 0 on interrupt - doesn't work
#include <avr/io.h>
#include <avr/interrupt.h>

void setup(){
  TCCR5B = (1 << CS52)|(1 << CS50); //Setting frequency divider to divide by 256
  OCR5A = 62500; //Delay of 1 second
  
  TCCR5A = 0; //Channel A disabled;
  TCCR5B |= (1 << WGM22); //CTC mode on channel B;
  
  TIMSK5 = (1 << OCIE5A); //Call interrupt when timer triggers
}

bool on;

ISR(TIMER5_COMPA_vect){
  //TCNT2 = 0; - doesn't work
  digitalWrite(13, on ? HIGH : LOW);
  on = !on;
}

void loop(){

}

On my board this code causes LED to flicker each cycle, after timer had triggered for the first time.

Try this:

   cli();
    TCCR5A = 0x00;
    TCCR5B = (1<<WGM52)|(1<<CS52);     //CTC, div 256
    OCR5A  = 31249;
    TIMSK5 = (1<<OCIE5A);
    sei();

and the variable used within ISR should be volatile to be sure the value is stored into memory and not just in the register.

Budvar10:
Try this:

    TCCR5A = 0x00;

TCCR5B = (1<<WGM52)|(1<<CS52);    //CTC, div 256
    OCR5A  = 31249;
    TIMSK5 = (1<<OCIE5A);




and the variable used within ISR should be volatile to be sure the value is stored into memory and not just in the register.

Amazing! Looks like the problem was that i accidentally applied WGM22 flag isntead of WGM52. Thanks for help!

Also prescaler, if you want 256 and top value should be -1, to be exact (I know the 31249 is a big number and clock frequency is not perfect). See the datasheet.