2

I am intending to write a code where a user will send lines through serial to affect timer interrupts. I am noticing a problem with serial where as soon as I enable the timer interrupts, the serial communication becomes garbled. More specifically, as soon as I enable the timer interrupts and I open the serial monitor, the monitor gets flooded with garbage. I haven't written too much code and this is already happening. Am I making a silly mistake? I am using an Arduino Mega 2560. My code is below:

void setup() {
 Serial.begin(9600);
 Serial.println("Hello World!");
 timer_setup();
}
void loop() {
 // put your main code here, to run repeatedly:
}
void timer_setup() {
 // waveform generation = 0100 = CTC
 TCCR1B &= ~(1 << WGM13);
 TCCR1B |= (1 << WGM12);
 TCCR1A &= ~(1 << WGM11);
 TCCR1A &= ~(1 << WGM10);
 // output mode = 00 (disconnected)
 TCCR1A &= ~(3 << COM1A0);
 TCCR1A &= ~(3 << COM1B0);
 // Set the timer pre-scaler
 TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
 OCR1A = 0x4000;
 TCNT1 = 0;
 // Enable timer interrupt mask 1
 TIMSK1 |= (1<<OCIE1A);
}

If I comment out the TIMSK1 |= (1<<OCIE1A) line, serial doesn't mess up.

asked Mar 28, 2016 at 6:17

1 Answer 1

4

You've enabled interrupts for Timer 1 Compare A interrupt. Where is the interrupt handler?

For example:

ISR(TIMER1_COMPA_vect)
{
 // whatever
} // end of TIMER1_COMPA_vect

Without that, the processor is just restarting. No wonder serial output is messed up.

answered Mar 28, 2016 at 7:22
2
  • Thanks, Nick. I hadn't added it yet because I wasn't testing interrupts yet, just setting it up. I didn't know it would do that if I didn't include the handler. Commented Mar 28, 2016 at 11:44
  • 1
    You can't "set up" interrupts without a handler and expect things to work. Once you enable the flag, you are promising something will handle them. The compiler generates a default handler that jumps to the start of the program (same place Reset goes). Commented Mar 28, 2016 at 20:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.