Muppetry with Interrupts

Hi Gang

I’m posting in the help that someone can offer me some assistance with the basics of getting timer based interrupts working on the Mega2560 board.

My longer term aim is to have Timer0 (8 bit) counting an external 32.768KHz clock and dividing it by 256 through calling the ISR every 256 external pulses (128 times per second).

However, due to some spectacular Muppetry, I can’t get even a basic ISR to run. Here’s the code I would like help with:

#define ledPin 13

void setup()
{
  Serial.begin(9600); 
  
  pinMode(ledPin, OUTPUT);

// initialize Timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;

OCR1A = 31250; // compare match register 16MHz/256/2Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}

ISR(Timer1_COMPA_vect) // timer compare interrupt service routine
{
  Serial.println("Inside ISR");
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
}

void loop()
{
  Serial.println("Inside Main Loop");
  delay(20000);
}

All I see in the serial monitor is the text output from the main loop and no activity on pin 13.

Can anyone (gently) point out what’s going on here?

Thank you,

Mark.

ISR(Timer1_COMPA_vect) // timer compare interrupt service routine
{
  Serial.println("Inside ISR");

Muppetry indeed.
Don't do interrupt-driven stuff when interrupts are disabled.

Could you perhaps elaborate a little?

Serial I/O is interrupt driven.
Interrupts are disabled inside ISRs.
Don't do interrupt-driven stuff when interrupts are disabled.

OK, thought so and understood.

I only added that out of desperation. Here is the code that (still) isn’t working:

#define ledPin 13

void setup()
{
  Serial.begin(9600); 
  
  pinMode(ledPin, OUTPUT);

// initialize Timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;

OCR1A = 31250; // compare match register 16MHz/256/2Hz
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}

ISR(Timer1_COMPA_vect) // timer compare interrupt service routine
{

  digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
}

void loop()
{
  Serial.println("Inside Main Loop");
  delay(20000);
}

Thanks for any help…

Mark