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.
1 Answer 1
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.
-
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.Sebastian Freeman– Sebastian Freeman2016年03月28日 11:44:07 +00:00Commented Mar 28, 2016 at 11:44
-
1You 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).2016年03月28日 20:32:13 +00:00Commented Mar 28, 2016 at 20:32
Explore related questions
See similar questions with these tags.