Author Archives: Shawn Hymel

Adventures in Science: Level Up Your Arduino Code With Timer Interrupts

via SparkFun: Commerce Blog

Previously, we looked at using registers directly in Arduino and setting up external interrupts. This time, we configure a timer interrupt to toggle an LED every 0.5 seconds. That’s right; we’re going to redo blinky the hard way.

The ATmega328P has three timers that continually increment. Note that Arduino uses them for various functions, which means you probably don’t want to use those functions if you plan to mess with the timers. On the UNO and RedBoard, you will find:

Name Size Possible Interrupts Uses in Arduino
Timer0 8 bits
(0 - 255)
Compare Match
delay(), millis(), micros()
analogWrite() pins 5, 6
Timer1 16 bits
(0 - 65,535)
Compare Match
Input Capture
Servo functions
analogWrite() pins 9, 10
Timer2 8 bits
(0 - 255)
Compare Match
analogWrite() pins 3, 11

Each of these timers can be configured for one or more interrupts:

  • Compare Match — When the timer value reaches a specific value (stored in the corresponding output compare register), an interrupt will be generated. This can be useful for creating pulse width modulation (PWM) signals on pins or sampling a sensor at specific intervals.
  • Overflow — When the timer rolls over from its max value (e.g., 65,535) to 0, an interrupt is generated. Overflow interrupts are also used for PWM signals and running pieces of code at precise intervals.
  • Input Capture — When a specific pin changes value (e.g., ICP1), the current timer value is stored in another register (ICR1) that can be retrieved later to see the exact time that event occurred. This type of interrupt is good for measuring the time between pulses.

To help make timing longer events easier (especially when some of the timers can only count up to 255), a prescaler can be used. A prescaler, in effect, divides the system clock to make something operate more slowly. For example, here is Timer1 counting up to 15 with no prescaler. You can see how Timer1 increments on every rising edge of the system clock.

No prescaler on a timer in Arduino

If we set a prescaler of 8, we can see how the timer counts up at a much slower pace. The timer only increments once for every 8 counts of the system clock.

Prescaler of 8 for a timer in Arduino

Knowing that we have a 16MHz clock on the Arduino UNO and RedBoard, we can calculate what kind of prescaler we need and to what value we need to count to trigger an interrupt every 500ms. Timer1 supports four different prescalers in addition to no prescaler (directly connected to the system clock): 8, 64, 256, 1024. We can find these by looking at the TCCR1B register description in the ATmega328P datasheet. We can multiply the desired delay by the clock speed and divide that answer by the prescaler to get the number of required timer counts. If we use a prescaler of 256, we see that we need 31,250 counts:

Prescaler to counts calculation in Arduino

We set the prescaler to 256 and load 31,250 into the OCR1A register. Don’t forget to set the output compare A interrupt enable bit in TIMSK1 and enable global interrupts! Now, whenever Timer1 reaches 31,250, a TIMER1_COMPA interrupt will occur. Create your ISR to toggle the LED and reset the timer.

// Pins
const int led_pin = PB5;

// Counter and compare values
const uint16_t t1_load = 0;
const uint16_t t1_comp = 31250;

void setup() {

  // Set LED pin to be output
  DDRB |= (1 << led_pin);

  // Reset Timer1 Control Reg A
  TCCR1A = 0;

  // Set to prescaler of 256
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  // Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  // Enable Timer1 overflow interrupt
  TIMSK1 = (1 << OCIE1A);

  // Enable global interrupts

void loop() {

  TCNT1 = t1_load;
  PORTB ^= (1 << led_pin);

Timers are extremely powerful and useful microcontroller functions. They allow you to sample, control hardware or measure signals at very precise intervals.

Outside of the already given Arduino functions (delay(), millis(), servo, tone, etc.), how else have you used timers in your microcontroller projects?

comments | comment feed

Adventures in Science: Level Up Your Arduino Code With External Interrupts

via SparkFun: Commerce Blog

Last time we looked at Arduino code, we examined how registers worked in the ATmega328P. We continue peeking under the hood to see how to set up external interrupts using direct register writes.

An interrupt is anything that can stop the main execution thread of a program and cause the processor to perform some action before returning to that main thread. In the case of external interrupts, something like a button push can be configured to cause this brief pause to allow some other piece of code to run.

In the ATmega328P, program memory is divided up into three main sections:

  1. Interrupt Vector Table (IVT) — Tells the processor where to jump to find the interrupt service routine (ISR) for each interrupt source (e.g., Port D, Pin 2 falling edge).
  2. Program Space — This is where your main program lives. Any ISRs you write will also live here.
  3. Bootloader — Optional section of code that runs first on a microcontroller that allows you to send new programs to it through nontraditional means (e.g., over the UART port instead of the ISP port). It can be configured to do other things, but being able to load programs over UART is what makes Arduino work so nicely.

When you give power to (or reset) your ATmega328P, the very first instruction that’s loaded is at program memory address 0x0000. This just happens to be the RESET vector. Usually, the only instruction there is a jump command to another place in memory (usually 0 x 0034 — the start of your program space). Your program begins executing sequentially from there. Part of the setup code might be telling the processor that you are open to an external interrupt when Port D, Pin 2 (also known as interrupt source “INT0”) experiences a falling edge (logic HIGH to logic LOW).

Note that you generally need three things to happen to have the interrupt trigger:

  1. Global interrupts must be enabled (in AVR, this is accomplished with the sei() function). Note that global interrupts are enabled by default in Arduino.
  2. The individual interrupt must be enabled (usually by setting a bit in a particular register associated with that interrupt).
  3. The interrupt condition must be met (e.g., a falling edge on a particular pin).

Once all three of these conditions are met, the interrupt will trigger. Execution on your main program will stop, any state variables or numbers the processor was working on are saved to memory, and execution jumps to the IVT. Which entry in the table it moves to is based on which interrupt triggered. For example, a falling edge on Port D, Pin 2 is the INT0 interrupt, so execution will jump to address 0 x 0002 (see the Reset and Interrupt Vectors table in the ATmega328P datasheet).

Often, only a single instruction will reside at the interrupt address. This is normally a jump command to somewhere else in program memory, which is where the ISR resides. The memory location of the ISR is known as an “Interrupt Vector.” So, our processor will jump to the ISR, perform whatever instructions it finds there, and then jump back to the main program to pick up where it left off (restoring any saved variables it might have previously stored).

How external interrupts work in an Arduino ATmega328p

External interrupts are great for responding to things like button pushes in a timely fashion or waking from a sleep state when a sensor has data to be read.

How else have you used interrupts? Why do you find them so important in microcontroller development?

comments | comment feed