[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

2112
TotesMessenger•

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)

3
Zoudenprofessional tinkerer•

Thanks for taking the time to write this! But isn't this just a roundabout way of achieving the same thing as blink-without-delay, which uses the interrupt-driven millis()?

There's an explanation here: https://www.baldengineer.com/blink-without-delay-explained.html

1†
asking_scienceOP•

a roundabout way

It's exactly the opposite. Blink-without-delay is based on the same principles but implemented in a roundabout, convoluted manner, whereas this is bare-bones, cut-to-the-chase. You're not going to get much faster than this. Besides, here you have full control, full power, whereas millis() gives you the illusion of power.

Edit: I've just again read through the millis() source code and to my dismay remembered that the function -- without asking or checking -- just shits all over all pre-set prescalers, as well as interrupt masks, for TIMER0, 1 and 2. How rude. Also, unlike millis() which caters in general, the code above is optimised for use-case, and lends itself well to processor time, memory and energy efficiency.

5
Zoudenprofessional tinkerer•

That's not the source code for the arduino function. The arduino code is in wiring.c - there's a discussion of it here. It only uses timer0. It's actually very similar to your code, with a bit extra to make the overflow correspond to real-world milliseconds.

But yes, it sets the prescaler for timer0.

0
Jeffdk•

This is wrong. That's not the source code.

0
Jeffdk•

Meh... Why would you prefer this? I mean, instead of a state machine like setup (not the delay). I can understand there might be specific situations.

0
asking_scienceOP•

Can you elaborate? I'm not sure I understand what you mean?

0
Jeffdk•

The blink-without-delay is actually a perfect (but very basic) example of a state machine.

0
asking_scienceOP•

It actually isn't, but it could be if some of the code is re-arranged. For example, in B-W-D, the decision to turn on the LED is made based on a time interval (not how state machines work), and not by a state transition (how state machines actually work). If the ISR set the variable ledState, then the loop() function would react according to the current state which was set in the ISR, then one might start calling it a state machine.

0
Jeffdk•

The timing isn't what makes it a state machine. For example, one of my robots checks it sensors (among a lot of others things) 10 times per second. Setting flags every loop. Other routines may act on these flags, during the same loop.

0