I am trying to write an Arduino code to blink LED using timer 4 on Arduino MEGA (atmega2560). I resetted the timer registers, and entered all the necessary values to bring to 16MHz to 1Hz (rescalar = 1024, OCR4B = 15624), then I wrote the blinking code inside the service routine block. Now when I run the program, the ISR is called only once. I saw from Youtube videos that even though the setting up of TCCR registers and TIMSK is in setup() function, it repeats indefinitely like a loop. Below is my code. Any help would be immensely appreciated. Thank you.
int led_pin = 10;
static int counter = 0;
int led_blink = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(led_pin,OUTPUT);
cli();
TCCR4A = 0;
TCCR4B = 0;
TCNT4 = 0;
OCR4B = 15625; //set the maximum count 16MHz -> 1Hz
TCCR4B |= (1<<CS10) | (1<<CS12) | (1<<WGM12); // prescalar = 1024 , CTC(OCR3B) mode
TIMSK4 |= (1<<OCIE4B);
sei();
interrupts();
}
ISR(TIMER4_COMPB_vect)
{
Serial.println(millis());
led_blink = !led_blink;
}
void loop() {
// put your main code here, to run repeatedly:
if(led_blink == 1)
digitalWrite(led_pin,HIGH);
}
millis()?digitalWriteis very cheap, and having it in the ISR shouldn't make problems, butSerial.printlnis a very complex function that on itself uses timers and takes several ms to execute.