Any timer interrupt examples for Mega2560?

Hi

I am looking for a code example using timer interrupts with the ATMega2560, but haven't found any. Does anyone know of any?

When reading up on interrupts, I have noticed it says that it works slightly different on the Mega.

I have an Arduino Mega ADK and would like to try interrupts using timer 4 or 5.

Thanks

Well, I tried a longshot and used an Arduino Uno example, just swapping timer1 for timer4, and what do you know, it worked. :slight_smile:

So here's the modified code I used.

//timer interrupts
//by Amanda Ghassaei adapted by T.Nilsson July 2019 :)
//June 2012
//https://www.instructables.com/id/Arduino-Timer-Interrupts/

/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
*/

//timer setup for timer4
//For arduino Mega

//timer4 will interrupt at 1Hz

//storage variables
boolean toggle4 = LOW;

void setup(){
 
 //set pins as outputs
 pinMode(13, OUTPUT);

cli();//stop interrupts

//set timer4 interrupt at 1Hz
 TCCR4A = 0;// set entire TCCR1A register to 0
 TCCR4B = 0;// same for TCCR1B
 TCNT4  = 0;//initialize counter value to 0
 // set compare match register for 1hz increments
 OCR4A = 15624/1;// = (16*10^6) / (1*1024) - 1 (must be <65536)
 // turn on CTC mode
 TCCR4B |= (1 << WGM12);
 // Set CS12 and CS10 bits for 1024 prescaler
 TCCR4B |= (1 << CS12) | (1 << CS10);  
 // enable timer compare interrupt
 TIMSK4 |= (1 << OCIE4A);

sei();//allow interrupts

}//end setup

ISR(TIMER4_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)

 digitalWrite(13,toggle4);
 toggle4 = !toggle4;

}
 
void loop(){
 //do other things here
}

Thanks for taking the time to post an update and share the solution you found Thomasx.

Cannot say how much this post has helped a very stuck man!! Thank you!!