[Programming Tips] - How to use Interrupts (in stead of delay())
This post refers to the ATMega328P on which the code was tested, but should also apply to many/most Atmel mcus. Page and section references refer to the ATMega328P User's Manual. 'MCU' means 'microprocessor'.
#Timers gonna time
The ATMega328P MCU (Arduino UNO, ProMini, etc.) has 3 built-in timers, aptly named TIMER0 (p.125), TIMER1 (p.149) and TIMER2 (p.189). TIMER0 and TIMER2 are 8-bit, and TIMER1 is 16-bit. Among other purposes, these timers are used in ADC operations, for generating PWM and for raising interrupts. It is often the case that not all timers are being used at the same time, leaving one free to be used for the specific task of triggering the execution of a certain section of code after some delay (once-off) or repeating periodically.
In this example the MCU is running at 8MHz and TIMER2 is be used.
Overflow Interrupt
Each timer has associated with it a "counter" - a register that can hold a value. In the simplest case, this counter is incremented by 1 on every clock cycle. If the MCU is running at 8MHz (8,000,000 clock cycles per second), then the counter will be incremented 8,000,000 times per second. As mentioned earlier, TIMER0 and TIMER2 are 8-bit, and TIMER1 is 16-bit, which means that TIMER0 and TIMER2 can only count up to 255 (0xFF) before overflowing (then restarting again from 0), whereas TIMER1 can count up to 65535 (0xFFFF) before overflowing and restarting. Whenever a counter overflows, it automatically sets a flag in a register watched by MCU, and if you, the progammer, want something to happen when that interrupt flag is raised, then you must enable the TIMER2_OVF interrupt (p.211) and include an ISR (Interrupt Service Routine) in your code. The ISR is called automagically when its associated interrupt is raised, and it interrupts normal programming (hence the name).
At 8MHz, an 8-bit counter will overflow 31,250 times a second (31.25kHz) and at 16Mhz it will be 62,500 times per second (62.5kHz). To time an event, the number of overflows are counted. If you are timing things in milliseconds or hundredths of a second then this is perfectly fine, but if you intend to measure in seconds, or minutes, the counts can get very high and keep the MCU very busy with counting. The solution to this is to enable the prescalers (p.206) which scale the timer's clocking frequency down from the 'main' oscillator frequency (referred to as Fosc in the manual). The Fosc is scaled down by a factor of 1, 1/8, 1/32, ... 1/1024. At the lowest setting, that is 1/1024, the 8-bit TIMER2 counter overflows at about 30.518Hz This is much more manageable and leaves a lot of time for the MCU to perform other tasks, or save energy by sleeping.
Starting with a new sketch, try the following
#define TCCR2B _SFR_MEM8(0xB1)
#define TIMSK2 _SFR_MEM8(0x70)
ISR(TIMER2_OVF_vect);
bool lucky;
volatile int overflow_counter;
void setup()
{
lucky = false;
overflow_counter = 0;
//--------set up prescaler to 1/1024 of Fosc
//8MHz --> 7.8125kHz
//16MHz --> 15.625kHz
//don't worry, your MCU isn't running slower ;)
TCCR2B |= _BV(CS22) | _BV(CS21) | _BV(CS20); //p.206
//--------enable interrupt
TIMSK2 |= _BV(TOV2); //p.211
}
void loop()
{
//--------ask yourself this: do I feel lucky?
if (lucky)
{
//interrupt triggered, now do something
lucky = false; //reset
}
// * other stuff here (NO 'delay()'s!) * //
}
ISR(TIMER2_OVF_vect)
{
//--------increment on overflow
overflow_counter++;
//At 8MHz prescaled to 7.8125kHz, the counter overflows
//at 30.518Hz, so in 5 seconds, it overflows 152.588 times
if (overflow_counter == 153)//5 seconds have now passed
{
lucky = true;
overflow_counter = 0; //reset if you want it to repeat
//or uncomment the next line to disable the interrupt
//TIMSK2 &= ~(_BV(TOV2));
}
}
As some of you might have noticed by now, this is also a very handy way of generating custom PWM.
Posted Apr 30, 2019, 11:51 AM UTC · edited
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
^(If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads.) ^(Info ^/ ^Contact)