Hello, I am trying to be able to re-enable and disable an interrupt on runtime. However very first interrupt is triggered prematurely. The code running on a nano. I don't use any gpio pin except 5v and gnd. I am powering it externally and connected to it through usb(5v cutted off). I couldn't understand the reason. Maybe someone fimiliar with? Thanks in advance!
I know that it is not wise to use Serial in ISR but the situation is still the same without them(+ micros) . Just to show the problem better.
Code:
The timer setup seems nonsensical. This does nothing at all:
TIMSK1 |= (0 << OCIE1A);
Here is a working example to set up AVR TIMER1 for 100 Hz interrupts:
#define SAMPLE_HZ 100
void initTimer() { // set up 100Hz interrupt
// Start timer1 for periodic interrupt
noInterrupts();
TCCR1A = 0; //essential to clear this first with Arduino!
TCCR1B = 0;
TCNT1 = 0;
OCR1A = F_CPU / 256 / SAMPLE_HZ;
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS12); // 256 prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts();
}
ISR(TIMER1_COMPA_vect) { // called every 10mS
flag = 1; //set external flag
}
You MUST not print, or do any serial I/O in an interrupt routine. Interrupts are off, and communications generally depend on interrupts. You SOMETIMES get away with serial printing in Arduino, because the system programmers put in a kluge that allows it to work, a little bit.
@anon94801460 I have a question, in datasheet I see two compare register, OCR1A and OCR1B. Is it possible to use two different frequencies on them, with same prescaler, and using TIMER1_COMPAB_vect too?