Click here for a free subscription to "HDE" our site newsletter.

Arduino Timer Interrupt Example

Reentrant interrupts are not hard to use

See the full range of Arduino products

There are countless examples of Arduino sketches on the Internet covering all but the most obscure and complicated projects. Most of these sketches or programmes concentrate on getting the job done in the main loop() function and rarely venture into the world of interrupts.

I'm going to show you how you can take advantage of internal timer interrupts on the Arduino using a couple of LED's and a simple code sketch. Not only will I show you how to get a regular timed interrupt to work but I will also demonstrate the advantages of reentrant routines. That is interrupts that are allowed to interrupt themselves.

It is true that interrupt use can lead to unpredictable code behaviour that is difficult to debug but they can also greatly enhance your projects if you follow a few simple rules.

Why use interrupts in your Arduino projects

In general most tasks can be accomplished without resorting to interrupts but if you do then the use of interrupt service routines can clean up your code and add another dimension to your programmes. ISRs can be used to:

  • Provide a fast response to external inputs and user interface.
  • Free up your main loop for other things instead of sitting in delay functions.
  • Provide accurate timing in conjunction with hardware timers.

Things you need to play with timer interrupts

Arduino Uno Single Board Microcontroller

A computer on a board with everything you need to start running programs and interfacing with the real world. Includes CPU, flash, EEPROM and static RAM memory,digital and analog I/O, timers and more.

LEDs

Not only are they fun devices but you can use LEDs in most circuits for indicating state at various points. A well placed LED can give you an awful lot of information about what is happening in your circuit. Magic when things are not working exactly how you think they should.

Solderless BreadBoard

An 830 point breadboard is overkill for this simple demonstration project but I find that this size of breadboard is convenient for all kinds of projects.

Hook-Up Jumber Cable Wires

You can make these yourself with some flexible wire, solid copper wire and heat shrink sleeving if you can be bothered to spend the time soldering them all up. Why not make your life easier and buy a fistfull instead. They are not expensive.

The LED Interrupt Circuit diagram

Arduino Timer Interrupt Circuit Diagram
Simple Arduino Interrupt Demonstrator

Connect up the circuit

Arduino Timer Interrupt LED board image
Arduino Interrupt LED Connections

Buy an Arduino Uno now and start building smart electronics projects

Download and install the Arduino Timer One library

It is perfectly possible to write code that directly interfaces with the hardware including the internal ATmega328 timers on the Arduino. This would have been an interesting exercise but it isn't really what this guide is all about and there is a convenient code library available that does just what we need.

This demonstration is based on The ATmega328's Timer 1 so you should download and install the TimerOne library as below.

Download the timerOne library from https://code.google.com/p/arduino-timerone/downloads/detail?name=TimerOne-v9.zip&can=2&q= and install it using the guide https://arduino.cc/en/Guide/Libraries

Copy and paste the Arduino interrupt demo sketch below

Load the sketch onto your Arduino Uno and let it run. Both LED's will flash regularly. LED D1 will flash every 4 seconds and LED D2 will flash 5 times a second

What is happening here?

If you you speed up the flashing rate by adjusting the values of "TIMER_US" and "TICK_COUNTS" you can observe the pulses on an oscilloscope. If you don't have an oscilloscope you can build yourself one very cheaply using my book as a guide: Sound Card Oscilloscope: Build Better Electronics Projects.

When the sketch initializes and setup() is run, the ATmega328's timer 1 is set to interrupt every 100ms and every time it interrupts the state of LED D2 is toggled making it flash on and off 5 times a second.

Arduino Timer 1 reentrant interrupt timing
Reentrant timer 1 timing diagram

The interrupt service routine timerIsr() counts down a timer variable starting at 20. When it reaches zero the function tick_2s_isr() is called. This routine is called every 2 seconds as a result. But the tick_2s_isr() function contains a time consuming loop which takes much longer than 100ms so how is it that the interrupt routine can keep flashing D2? It can do this because tick_2s_isr() enables interrupts using the interrupts() function. When interrupts are enabled the timerIsr() is able to service every interrupt even though it calls a function that takes a long time to process. The interrupt ISR is said to be reentrant.

Now what would happen if tick_2s_isr() did not enable interrupts so there was no way for the function to be reentered? Try it. Comment out the lines with "interrupts()" and "noInterrupts()" like this:

// interrupts();
...
// noInterrupts();

Load and run the sketch and you should see that LED D2 now has to pause until the tick_2s_isr() completes before it flashes. The time between calls to the tick_2s_isr() function also increases due to the ISR not maintaining the regular count.

Arduino Timer 1 non reentrant interrupt timing
Non reentrant timer 1 timing diagram

Follow the rules of interrupts

The Arduino is an amazing little microcontroller board that could easily find use in the most sophisticated of electronic systems and yet it is so cheap and easy to use. The low cost and easy programming make this board perfect for hobby electronics projects and the ability to use interrupts is an awesome capability but you do have to follow some rules.

  • Keep processing in your interrupt service routines to a minimum
  • Never allow an interrupt task to reenter time consuming code before it has finished.
  • Be careful where you enable and disable interrupts
  • Always think "What can go wrong" - Because it will.

Now subscribe to our newsletter and don't miss a thing
 



Comments (5)

Topic: Arduino Timer Interrupt Example
Full StarFull StarFull StarFull StarHalf Star 4.5/5 (3)
Facebookdel.icio.usStumbleUponDiggGoogle+Twitter
Full StarFull StarFull StarFull StarEmpty Star
andry rakotomanana (Madagascar) says...
Hi,
I want to perform a tempearatur saver (which saves data every 60s)) and dispaly it with lcd!
would you please help me!
thanks
9th September 2018 7:25am
cristian torres (Colombia) says...
How did you calculate 20 = 2 seconds, because if we change 100 ms by another value automatically the 20 seconds also change
22nd October 2017 7:24am
Full StarFull StarFull StarFull StarFull Star
cristian torres (Colombia) says...
if (!(--tick_count))? What this means ? I know it is a counter but why tick count is 20 if you are counting 2s, and why you use ! or is the same to say for(tick_count=20;tick_count=0;tick_count --){

}
22nd October 2017 6:51am
Jesus Bermudez says...
Smile
Now I know what interrupts are!
15th October 2016 6:18am
Full StarFull StarFull StarFull StarFull Star
Tim Lastfogel (US) says...
Extremely educational
22nd November 2014 3:41pm

Add Comment

* Required information
(will not be published)
 
Bold Italic Underline Strike Superscript Subscript Code PHP Code Quote Insert line Bullet list Numeric list Link Email Image Video
 
Smile Sad Huh Laugh Mad Tongue Crying Grin Wink Scared Cool Sleep Blush Unsure Shocked
Captcha
Refresh
 
Enter code:
 
Notify me of new comments via email.
 
Remember my form details on this computer.
 
I have read and understand the privacy policy. *
 
I have read and agree to the terms and conditions. *
 
Click here for a free subscription to "HDE" our site newsletter.