Arduino Timer Interrupts

by Bart Pelgrims on July 9, 2012

Bike SpeedometerTimer interrupts allow you to perform a task at very specifically timed intervals regardless of what else is going on in your code.  In this instructable I’ll explain how to setup and execute an interrupt in Clear Timer on Compare Match or CTC Mode.  Jump straight to step 2 if you are looking for sample code.

Normally when you write an Arduino sketch the Arduino performs all the commands encapsulated in the loop() {} function in the order that they are written, however, it’s difficult to time events in the loop().  Some commands take longer than others to execute, some depend on conditional statements (if, while…) and some Arduino library functions (like digitalWrite or analogRead) are made up of many commands.  Arduino timer interrupts allow you to momentarily pause the normal sequence of events taking place in the loop() function at precisely timed intervals, while you execute a separate set of commands.  Once these commands are done the Arduino picks up again where it was in the loop().

Interrupts are useful for:

Measuring an incoming signal at equally spaced intervals (constant sampling frequency)
Calculating the time between two events
Sending out a signal of a specific frequency
Periodically checking for incoming serial data

There are a few ways to do interrupts, for now I’ll focus on the type that I find the most useful/flexible, called Clear Timer on Compare Match or CTC Mode.  Additionally, in this instructable I’ll be writing specifically about the timers to the Arduino Uno (and any other Arduino with ATMEL 328/168… Lilypad, Duemilanove, Diecimila, Nano…).  The main ideas presented here apply to the Mega and older boards as well, but the setup is a little different and the table below is specific to ATMEL 328/168.

There are 2 example projects included in this instructable, a bike speedometer and serial communication over USB with your computer.

Serial usb keypad video:

The very detailed instructions are on the intstructable website.

Comments on this entry are closed.

Previous post:

Next post: