Timers, counters and interrupts
Hardware timers and counters (prescaler, overflow, CTC, input capture, 8051 modes), interrupts and the watchdog, with preload, compare-value and frequency-measurement calculations.
Drafted with Aria, reviewed by the AiCanCode.org team. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Sampling a sensor every millisecond, measuring a shaft's speed from encoder pulses, generating a stepper's step train or running a control loop at a fixed rate all rely on hardware timers and interrupts. Software delay loops waste the CPU and drift; a timer plus an interrupt gives exact, repeatable timing while the processor does other work.
Key ideas
Timer vs counter. A timer/counter is a hardware register that increments (or decrements) on each input pulse. If the pulses come from the internal clock (through a prescaler), it is a timer — its count measures time. If they come from an external pin, it is a counter — its count measures events (bottles, encoder edges).
Prescaler. A divider between the clock and the timer. With a prescaler N_pre, one timer tick lasts N_pre/f_clk. A larger prescaler gives longer maximum intervals but coarser resolution.
Operating modes.
- Overflow (normal) mode: an n-bit timer counts up to 2ⁿ − 1, rolls over to 0 and sets an overflow flag. To get a chosen interval, preload the register so it overflows after the wanted number of ticks.
- Compare / CTC mode: the timer is compared with a compare register (OCR) every tick; on a match it sets a flag, can toggle a pin, and clears to 0. This gives an exact period with no software reload.
- Input capture: on an edge at a capture pin the current count is latched into a capture register — used to measure period, pulse width or speed.
- PWM: compare-match logic sets and clears a pin each period (next-but-one topic).
8051 timers. Timer 0 and 1 count machine cycles, f_osc/12 for the classic core (1 µs per tick at 12 MHz). Modes set in TMOD: mode 0 = 13-bit, mode 1 = 16-bit, mode 2 = 8-bit auto-reload (TH reloads TL — used for baud rates), mode 3 = Timer 0 split into two 8-bit timers. TR0/TR1 start them; TF0/TF1 are the overflow flags. Setting C/T = 1 makes it count pulses on the T0/T1 pin.
Interrupts. An interrupt is a hardware request that makes the CPU suspend the main program, save the return address (and on Cortex-M some registers), jump to an interrupt service routine (ISR) through a vector, and return afterwards.
- Sources: external pins (edge- or level-triggered), timer overflow/compare/capture, serial, ADC conversion complete, watchdog, and software interrupts/exceptions.
- Each source has an enable bit, a flag bit and usually a priority. A global enable must also be set.
- Polling vs interrupts: polling repeatedly checks a flag (simple, but wastes time and can miss short events); interrupts respond within a bounded latency.
- Latency = time from the event to the first ISR instruction; it depends on the instruction being completed, the hardware entry sequence, and any higher-priority ISR running.
- ISR rules: keep it short, no blocking delays or printing, clear the flag if the hardware does not, share data through
volatilevariables, and protect multi-byte shared data from being half-updated.
Watchdog timer. An independent timer that resets the MCU if software fails to "kick" it within its timeout — the standard recovery from a hung program in industrial products.
Connection to PLCs. PLC TON/TOF timers and CTU/CTD counters (later topics) are software timers built on the same idea: a time base and a count compared with a preset.
Formulas
T_tick = N_pre / f_clk
- T_tick = timer tick (s); N_pre = prescaler ratio; f_clk = timer input clock (Hz). For the classic 8051, f_clk = f_osc / 12.
T_max = 2ⁿ × T_tick
- Longest interval for an n-bit timer (s).
Preload = 2ⁿ − T_d / T_tick
- Value loaded for an overflow after delay T_d (s) in overflow mode; must be a non-negative integer.
f_int = f_clk / (N_pre × (OCR + 1)) → OCR = f_clk / (N_pre × f_int) − 1
- CTC (clear-on-match) interrupt frequency (Hz); OCR = compare register value.
Δ = (C₂ − C₁) mod 2ⁿ, T_sig = Δ × T_tick, f_sig = 1 / T_sig
- Input capture: C₁, C₂ = two captured counts (one rollover at most between them).
t_counter = N / f_pulse
- Time for an event counter to reach N counts at pulse rate f_pulse (Hz).
Worked examples
Example 1 (standard). A classic 8051 with a 12 MHz crystal must produce a 5 ms delay using Timer 0 in mode 1. Find TH0 and TL0.
T_tick = 12 / f_osc = 12 / 12 × 10⁶ = 1 µs.- Ticks needed = T_d / T_tick = 5 ms / 1 µs = 5000.
Preload = 2¹⁶ − 5000 = 65 536 − 5000 = 60 536= 0xEC78.
Answer: TH0 = 0xEC, TL0 = 0x78 (5000 ticks to overflow).
Example 2 (GATE level). An ATmega has a 16 MHz clock and a 16-bit Timer1 with prescalers 1, 8, 64, 256 and 1024. (a) Choose the smallest prescaler that allows a 1 s CTC interrupt and find OCR1A. (b) With prescaler 8, an input-capture unit records rising edges of a sensor signal at counts 64 000 and then 3464 (the timer rolled over once). Find the signal frequency.
- Ticks for 1 s with N_pre = 1: 16 × 10⁶ — far above 65 536. Minimum prescaler = 16 × 10⁶ / 65 536 = 244.1, so the smallest available is 256.
OCR1A = f_clk / (N_pre × f_int) − 1 = 16 × 10⁶ / (256 × 1) − 1 = 62 499(fits below 65 535). Tick = 16 µs.- Capture:
Δ = (3464 − 64 000) mod 65 536 = 5000ticks. T_tick = 8 / 16 × 10⁶ = 0.5 µs→T_sig = 5000 × 0.5 µs = 2.5 ms.f_sig = 1 / 2.5 ms = 400 Hz.
Answers: prescaler 256, OCR1A = 62 499; signal frequency = 400 Hz.
Common mistakes
- Forgetting the +1 in CTC mode: the period is (OCR + 1) ticks because counting includes 0.
- Loading the delay count instead of 2ⁿ − count in overflow mode.
- Forgetting the 8051's divide-by-12 (classic core) — enhanced single-cycle derivatives differ, so check the datasheet.
- Ignoring rollover in input capture; use unsigned subtraction modulo 2ⁿ.
- Picking a prescaler that makes the required count exceed 2ⁿ − 1, or a non-integer count that causes drift.
- Long ISRs (delays, printf) that block other interrupts and the main loop.
- Forgetting the global interrupt enable, or forgetting to clear a flag that software must clear, so the ISR re-enters endlessly.
For GATE ME
Timers appear in mechatronics as numericals on tick time, preload and compare values, maximum delay for a given register width and prescaler, event counting rates and frequency measurement, and as concept MCQs on interrupts (polling vs interrupt, vectors, priority, edge vs level triggering, watchdog). Practise converting carefully between µs and ms and checking that every computed count fits the register width.
Quick check
- A 16-bit timer runs at 16 MHz with prescaler 8. What is its overflow period?
- For an 8051 at 12 MHz in mode 1, what preload gives a 50 ms delay?
- In CTC mode at 16 MHz with prescaler 64, what OCR gives a 1 kHz interrupt?
- What does a watchdog timer do?
- Why is polling unsuitable for a 2 µs pulse on a busy MCU?
Answers: 1. 32.768 ms 2. 15 536 = 0x3CB0 3. 249 4. Resets the MCU if software fails to refresh it in time 5. The pulse may come and go between two polls; an edge interrupt latches it.
Interview questions
All Microcontrollers, PLC and Industrial Automation interview questionsTry answering each one aloud before you open it.
1.What is a timer in the context of microcontrollers and PLCs?Concept
A timer in microcontrollers and PLCs is a device or function that counts time intervals. It can be used to generate delays, measure time intervals, or trigger events after a specified period. Timers can be hardware-based, using a dedicated timer module, or software-based, implemented through programming.
2.Explain the role of counters in industrial automation.Concept
Counters in industrial automation are used to count events, objects, or operations. They can be used to track the number of products passing a point on a conveyor belt, count the number of operations a machine performs, or monitor the number of times a specific event occurs. Counters can be implemented in hardware or software and are essential for process control and monitoring.
3.What is an interrupt, and how is it used in microcontrollers?Concept
An interrupt is a signal that temporarily halts the normal execution of a program to execute a special routine called an interrupt service routine (ISR). Interrupts are used in microcontrollers to handle asynchronous events, such as input from a sensor or a timer overflow, allowing the microcontroller to respond quickly to external events without polling.
4.Why are timers used in PLCs for industrial automation?Application
Timers in PLCs are used to control the timing of operations and processes. They can be used to delay actions, create time-based sequences, or ensure that certain conditions are met for a specified duration. This is crucial in industrial automation for synchronizing processes, managing time-dependent tasks, and improving efficiency.
5.What happens if an interrupt is not properly handled in a microcontroller?Application
If an interrupt is not properly handled, it can lead to unpredictable behavior in the microcontroller. The program may not respond correctly to external events, leading to missed signals or incorrect processing. In severe cases, it can cause the system to crash or enter an infinite loop, affecting the reliability and safety of the application.
6.How do counters help in monitoring production lines?Application
Counters help in monitoring production lines by keeping track of the number of items produced, processed, or passing a certain point. This information is crucial for quality control, inventory management, and ensuring that production targets are met. Counters can also trigger alarms or actions if production deviates from expected levels.
7.Explain how a watchdog timer works in a microcontroller.Concept
A watchdog timer is a hardware timer that resets the microcontroller if the software fails to reset it within a specified time interval. It is used to detect and recover from software malfunctions, ensuring that the system can recover from unexpected errors or hangs. The microcontroller must periodically reset the watchdog timer to prevent a reset, indicating that the software is functioning correctly.
8.Calculate the time delay generated by a timer with a 1 MHz clock frequency and a prescaler value of 256, if the timer counts up to 1000.Numerical
To calculate the time delay, use the formula: Time Delay = (Prescaler × Timer Count) / Clock Frequency. Here, Prescaler = 256, Timer Count = 1000, and Clock Frequency = 1 MHz. Time Delay = (256 × 1000) / 1,000,000 = 0.256 seconds.
9.What is the effect of increasing the prescaler value on a timer's operation?Application
Increasing the prescaler value on a timer increases the time interval between timer increments, effectively slowing down the timer. This allows for longer time delays or intervals to be measured without changing the timer's count value. However, it also reduces the timer's resolution, as fewer increments occur within the same time period.
10.A counter in a PLC is set to count up to 500. If the input pulse frequency is 10 Hz, how long will it take for the counter to reach its maximum count?Numerical
The time taken for the counter to reach its maximum count can be calculated using the formula: Time = Maximum Count / Pulse Frequency. Here, Maximum Count = 500 and Pulse Frequency = 10 Hz. Time = 500 / 10 = 50 seconds.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?