I am working on timer interrupts and external interrupts. for external interrupts I understood the functions like attachInterrupt. detachinterrupt for individual interrupts ,noInterrupts() and interrupts() can be used to enable and disable all interrupts at a time.
But How to enable and disable timer interrupts??
I am writing a code for alarm clock and snooze button. So what I want is 1) whenever alarm time is equal to watch time, start a timer for 5 minutes and a buzzer buzzes. 2) whenever I press the snooze button, another timer starts and after 30 seconds a buzzer beeps. again I press snooze and again the timer starts and after 30 seconds buzzer beeps. 3) But after 5 minutes of the first timer, both timer interrupts gets disabled as now I dont want any buzzer.
I know how to initialize the timer in setup function, and I am getting the buzzes every 30 seconds. I also know that interrupts will come according to the timer value and I need to call the function after a fix number of counts or 30 seconds or 5 minutes.
But I dont know how to disable and enable timer interrupts wherever I want in code.
1 Answer 1
- Step 1: Read the datasheet for the chip.
- Step 2: Find the registers that control the timers and their interrupts.
- Step 3: Set or clear the relevant bits in those registers.
For example, the ATMega328P has the TIMSK1
register for Timer 1, which has three bits related to interrupts:
- Bit 2 – OCIE1B: Timer/Counter1, Output Compare B Match Interrupt Enable
When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1 output compare B match interrupt is enabled. The corresponding interrupt vector (see Section 11. "Interrupts" on page 49) is executed when the OCF1B flag, located in TIFR1, is set.
- Bit 1 – OCIE1A: Timer/Counter1, Output Compare A Match Interrupt Enable
When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1 output compare A match interrupt is enabled. The corresponding interrupt vector (see Section 11. "Interrupts" on page 49) is executed when the OCF1A flag, located in TIFR1, is set.
- Bit 0 – TOIE1: Timer/Counter1, Overflow Interrupt Enable
When this bit is written to one, and the I-flag in the status register is set (interrupts globally enabled), the Timer/Counter1 overflow interrupt is enabled. The corresponding interrupt vector (see Section 11. "Interrupts" on page 49) is executed when the TOV1 flag, located in TIFR1, is set.
So to turn off the Compare B Match interrupt you can use:
TIMSK1 &= ~(1 << 2);
And to turn it on again:
TIMSK1 |= (1 << 2);
Both Timer 0 and Timer2 have a TIMSKx
register which works in the same way.
millis()
) seems more appropriate, as you cannot program a hardware timer to fire more than about 4.2 seconds into the future.