Arduino Timer 3 interrupt setup

Hi,

I'm trying to set timer3 on a Arduino Micro but my interrupt isn't being called at the frequency I'm attempting to set it to (40Hz or 25ms period). When I run the code below my interrupt writes "here" 44572 times per second! Can anyone see where I'm going wrong in setting up the timer?

void setup()
{
  Serial.begin(115200);
  delay(2000); // Delay to allow for initialisation of serial
}

void loop()
{
  setupTimer3_25mS();
  delay(1000);
  disableTimer3();
  while(true);
}

void disableTimer3()
{
  //Disable timer
  TCCR3A = 0;
  TCCR3B = 0;
}

void setupTimer3_25mS()
{
  // Disable global interrupts
  cli();

  disableTimer3();
 
  // Set compare match register to desired timer count - 25ms 40Hz (16000000/1024/40 = 390.63)
  OCR3A = 391;

  // Turn on CTC mode WGM32 set CS10 and CS12 bits for Timer3 prescaler of 1024
  TCCR3B = bit (WGM32) | bit (WGM32) | bit (CS30);

  // Enable timer compare interrupt
  TIMSK3 |= (1 << OCIE3A);
  
  // Enable global interrupts  
  sei();
}

ISR(TIMER3_COMPA_vect) // Timer3 interrupt
{
Serial.println("Here");
}

Can anyone see where I'm going wrong in setting up the timer?

Your code does not implement the comment.

// Turn on CTC mode WGM32 set CS10 and CS12 bits for Timer3 prescaler of 1024
  TCCR3B = bit (WGM32) | bit (WGM32) | bit (CS30);
ISR(TIMER3_COMPA_vect) // Timer3 interrupt
{
Serial.println("Here");
}

Never call writing method of the HardwareSerial class (Serial object) inside an ISR. In interrupt context interrupts are blocked but the serial interface depends on interrupts to fulfill it's task. If it fills the internal buffer it will wait forever for the buffer to be cleared by the interrupt. As your ISR is called about 41000 times a second the buffer will fill up very quickly.

Hi @ cattledog, thanks for your reply! Unfortunately that was a typo - if you look at this link: MEAM.Design : ATmega32U4 : Timers/Counters : Timer 3 the prescaler for the timer is set using CS32, CS31 and CS30.

Hi @Pylon, thanks for your reply! I've only put the write to the serial object within the ISR in this case to try and determine if I've set the timer correctly to 40Hz. In my final code I will remove the write to the serial object from within the ISR as you suggest.

I was unclear. You want

 TCCR3B = bit (WGM32) | bit (CS32) | bit (CS30);

Mode 4 , top 0CR3A, 1024 prescaler

Hi @cattledog, thanks again for your reply - you're correct that's solved it! Thanks very much!