I'm learning how to use interrupts and created a small code to figure out how to work them. The code is supposed to print a counter to the serial monitor at a specific interval and flash the LED. The code uploads to the Uno but nothing appears on the serial monitor and the LEd doesn't flash. I have no idea what could be going wrong with it. Any ideas?
I have tried it on two different boards, so it isn't a bad Uno or anything.
volatile int counter = 0;
void timer1_init(){
noInterrupts(); // disable interrupt
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0; // initialize the counter from 0
OCR1A = 7811; // sets the counter compare value. Using timer1, Prescaler= 1024, Interrupt frequency = 2 Hz, Compare value=[16e6/2/1024]-1= 7811
TCCR1B |= (1<<WGM12); // enable the CTC mode
TCCR1B |= (1<<CS12)|(1<<CS10); //sets the control scale bits for the timer
TIMSK1 |= (1<<OCIE1A); //enable the interrupt
interrupts(); //allows interrupts
}
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, LOW);
Serial.begin(115200);
timer1_init();
}
ISR(Timer1_COMPA_vect) {
counter += 1;
Serial.print(counter);
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
}
void loop(){
}
Thank you.