Using Hardware Timers

Hardware Timers

Most microprocessors have one or more programmable hardware timers that include support for interrupts. There can be different types of timers intended for different applications. As an example, the LPC1768 has four 32-bit general purpose timers, a watchdog timer, a repetitive interrupt timer, a system tick timer, a quadrature encoder interface, 6 PWM outputs, and a real-time clock with support for interrupts. A brief introduction to the use of these timers in typical applications will be presented along with several code examples for mbed.
Some sensors such as this Sonar module above require accurate timing measurements

Watchdog Timer

A Watchdog timer (WDT) can be used to force an automatic processor reset whenever a software or hardware fault locks up a processor. A Watchdog timer example for the mbed LPC1768 platform is available. If the video demo does not play on the wiki page, use this link: Watchdog timers are recommended for safety critical applications.

General Purpose Timers

General purpose hardware timers can be used to time or count events using external I/O device signals. Software polling or interrupts can be used to start/stop/read the timer or counter. While interrupts may appear more complex, they can save processor time and power, and also provide more accurate timing measurements. The mbed APIs timer, ticker, and timeout can be used to control the hardware timers.

The mbed API InterruptIn is often used in timer code. It can force a function to be called when an external I/O pin changes state from low-to-high (rise) and/or high-to-low (fall) using interrupts. This is a handy, efficient, and accurate way to start, stop and read timers using external signals.

A timer case study with example code that measures pulse width on a sonar sensor using timers with and without interrupts is available for mbed. Timeout is also used to automatically trigger the next sonar measurement cycle. The pulse width on the echo signal pin indicates distance to the nearest target on the sonar sensor. Another timer case study example shows how to use timers to control solenoids, so that they turn off after a specified time period and do not overheat. Another timer example uses Ticker to playback audio using samples stored in a large array in on-chip flash memory. The timer generates an interrupt at the playback rate, the interrupt routine outputs the next audio sample, and the main program can still perform other tasks during audio playback since interrupts are used.

Hardware timers are typically used to measure short time durations in the us or ms ranges such as those seen in the sonar sensor example. For example, a 32-bit us timer/counter will overflow in about thirty minutes. If a timer is left running after reaching the maximum count many will continue counting again back at zero. Software will need to take this into account to compute the elapsed time, if it is possible for the timer to roll over or wrap around during a timing operation. On the mbed LPC1768, timer 3 is used to implement the mbed APIs wait, timer, ticker, and timeout.

Using Features not supported or used by mbed's APIs

Not all of the general purpose timers and features of the other timers/counters are supported by the mbed class APIs. For example, on the LPC1768 timers 0,1, and 2 are not used by the mbed timer APIs. Many timers have programmable clock inputs that can scale the clock or use an external clock. User programs will need to write their own functions to access this hardware. The easiest approach is to use the already setup I/O register names (i.e. pointers to structures in C++) after reading the processor manual's hardware documentation on timers and their I/O control registers. This approach is used in the WatchDog timer code example referenced earlier. Assembly language could also be used, but it is more difficult and takes a lot longer to code. Not all of a processor's I/O pins are available for easy breadboard use from the limited header pins, so using some features not supported by mbed APIs might require a custom PCB.

Using Timers to Count Events

A timer using an external clock (instead of an internal clock signal) can also function as a counter. Sometimes hardware timers with these external clock features are also called timer/counters. Some sensors require counting the number of pulses (and not just measuring the pulse width). In such cases a hardware timer with the pulse signal as the clock input can be used to count events at significantly higher rates than are possible using software polling or interrupts only.


One example is the Geiger Counter seen above. A particle passing through the gas in the Geiger tube generates a pulse. Geiger counters determine radiation levels in counts per minute (CPM). Geiger counters and radiation meters need to count these random pulses coming from a Geiger Tube sensor. The pulses are used to clock a timer (or counter) so that it winds up counting particles. A second timer is also often used to time/control the time period accurately to count events for a given time period.

A Geiger Tube can be used to measure radiation by counting the pulses per minute

Laboratory Frequency Counters are another example

PWM Controllers

Pulse Width Modulation (PWM) controllers contain hardware similar to timers. The major difference is that they are designed to provide external timing signal outputs for I/O devices. The mbed API, PwmOut controls PWM output signals. If a device does not have PWM hardware available, a timer with interrupt code can be used to produce PWM outputs. Typical applications include motor speed control, dimming LEDs, servos, and audio output. In some applications, extra PWM outputs can be used to provide timing signals such as clocks or pulses to other external I/O devices.

Quadrature Encoder Interface (QEI)

A quadrature encoder converts angular rotation into two pulse signals. They are widely used in motor control devices for feedback. By counting the number of pulses and the relative phase of the two signals, the position and the direction of rotation can be determined. Velocity can be measured using a timer. An up/down counter and a velocity timer for use with quadrature encoders is provided in many microcontrollers and is found the LPC1768’s QEI hardware unit. Many motor control systems use a quadrature encoder on the motor shaft for feedback input, and a PWM output to drive the motor. A PID control loop is common in such systems. Lower cost encoders found on small hobbyist robot kits often have only one rotational pulse output signal (i.e., no direction information - not two QE signals) and a general purpose timer can be used with these.

A geared 12V DC motor with an integrated quadrature encoder (in black housing above) from Pololu. As seen on the right above, the encoder produces 3,200 pulses per revolution on the output shaft.

Rotary Pulse Generators (RPG) such as the one above from Sparkfun are a common user input device that also uses a quadrature encoder. The two pulses are generated when the user rotates the knob. Mechanical encoders may need debouncing (like pushbuttons).


Many devices also include a Real-Time Clock (RTC) timer circuit that is more useful to measure longer time periods in the sec, minute, hour, day and even year ranges. The RTC often includes backup power features to continue running when power is off on the device. There are standard C++ time functions and data structures that are typically used to control the RTC.

A code example using the RTC hardware on the mbed LPC1768 platform is available. The LPC1768 RTC also has an alarm feature and 20 bytes of battery backup register storage.

RTOS system tick timer

A Real-Time Operating System (RTOS) uses a hardware timer to generate a periodic time slice interrupt that is typically in the ms range. On the LPC1768, the system tick timer is used for the time slice interrupt of 1ms. The time slice interrupt enables the RTOS scheduler to regain control of the processor and switch threads. This enables it to share processor time between multiple threads by stopping the current thread and switching to another thread that is waiting to run.

The RtosTimer class allows creating and controlling of timer functions in the system. When using the RTOS, ticker objects should be replaced with RtosTimer objects in most cases. A timer function is called when a time period expires whereby both one-shot and periodic timers are possible. A timer can be started, restarted, or stopped.

Repetitive Interrupt Timer

The Repetitive Interrupt Timer on the LPC1768 is a simple 32-bit Timer that provides a way of generating interrupts at fixed time intervals, without using one of the more complex general purpose timers. It is normally used for recurring interrupts that are unrelated to Operating System interrupts. One possible application would be to control sample periods using interrupts on A/D, D/A and other hardware. On the LPC1768, it is not used in the mbed timer APIs.

Wait() and Thread::Wait()

Sometimes an approximate software time delay is needed in programs. Wait() provides a software loop based delay using a timer. Wait() locks up the processor and should be replaced by Thread::Wait() whenever the mbed RTOS ver 2 is used. The RTOS can run other threads during a Thread::Wait() (but not during a Wait()! ). Thread::Wait() has a default argument of ms (not secs like Wait()). The RTOS scheduler needs to start running the thread again after a Thread::Wait()s time period has passed, so the actual time delay is often a bit longer when multiple threads are running.

Please log in to post comments.