The Improved Blinking LED Program

Now we will look at an interrupt example using a timer. For this example, we will use the Blinking LED code from Chapter 3. However, instead of using a loop to handle the timing of the LED blink, we will use a hardware timer. Most microcontrollers include up to several timers.

There are several advantages to using a timer rather than a loop for the timing: the processor is free to handle other tasks instead of sitting in a while loop doing nothing, a timer is more accurate for measuring a loop than a stopwatch, and you can calculate the exact time you want the timer interrupt to fire instead of using a trial-and-error approach based on the processor’s clock.

In this improved Blinking LED program, the delay routine is eliminated and a timer device driver is used to handle the delay between LED toggles. The timer is used to interrupt the processor once a specific interval has elapsed.

How Timers Work

A timer is a peripheral that measures elapsed time, typically by counting down processor cycles or clocks. A counter, by contrast, measures elapsed time using external events. A timer is set up by programming an interval register in the timer peripheral, with a specific value calculated by the software engineer to determine the timer interrupt interval. The timer peripheral then uses a clock to keep count of the number of ticks that have elapsed since the timer has been started. The number of clock ticks is compared to the value in the timer interval ...

Get Programming Embedded Systems, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.