Timers, interrupts and serial communication
Timers and PWM, 8051 timer modes and reload values, 8051/8085 interrupts, and UART, SPI and I2C serial communication with worked numericals.
Drafted with Aria, reviewed by the AiCanCode.org team. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
An instrument must sample at an exact rate, react at once to an alarm input and send its readings to a PC or PLC. Timers give the exact time base, interrupts give fast response without wasting the CPU in polling loops, and serial ports (UART, SPI, I²C) carry the data. Getting reload values, baud rates and interrupt priorities right is everyday embedded work and a regular GATE topic.
Key ideas
Timers and counters. A timer is a binary counter clocked from the processor clock (through a prescaler). Counting a known clock measures time; counting pulses on an external pin makes it an event counter (e.g. a flow-meter or encoder input). When the counter rolls over from its maximum to zero it sets an overflow flag and can raise an interrupt. Uses: periodic sampling ticks, delays, measuring pulse width or frequency (input capture), generating waveforms and PWM (output compare), and baud-rate generation.
8051 timers. Two 16-bit timers, T0 and T1, each a pair of 8-bit registers THx:TLx, controlled by TMOD (mode, timer/counter select, gate) and TCON (run bits TR0, TR1 and overflow flags TF0, TF1). In timer mode they count machine cycles (f_osc/12).
- Mode 0: 13-bit timer.
- Mode 1: 16-bit timer; reload by software after each overflow.
- Mode 2: 8-bit auto-reload; TLx counts and is reloaded from THx on overflow. Used for baud-rate generation.
- Mode 3: T0 split into two 8-bit timers. A timer counting up from initial value N overflows after (2ᵏ − N) counts, k being the mode width.
PWM. A timer counts from 0 to TOP and a compare register sets the output pulse width. Frequency f_PWM = f_tick/(TOP + 1); duty cycle D = compare/(TOP + 1). Averaged through the load (motor, heater, LED) or an RC filter, PWM acts as a simple DAC.
Interrupts. A hardware request makes the CPU finish the current instruction, save the PC on the stack, jump to a fixed vector address and run the interrupt service routine (ISR), returning with a return instruction (RET in the 8085, RETI in the 8051).
- Polling wastes CPU time and can miss short events; interrupts give fast, deterministic response.
- Maskable interrupts can be disabled globally or individually; non-maskable ones (8085 TRAP) cannot.
- Vectored interrupts jump to a fixed address; priority resolves simultaneous requests.
- 8051: five sources with vectors INT0 0003H, Timer 0 000BH, INT1 0013H, Timer 1 001BH, serial 0023H. Enabled through IE (EA global bit plus one bit per source); two priority levels set in IP; within a level the default order is INT0, TF0, INT1, TF1, serial. External interrupts can be level- or edge-triggered.
- 8085: TRAP (non-maskable, 0024H), RST 7.5 (003CH), RST 6.5 (0034H), RST 5.5 (002CH), and INTR (non-vectored; the device supplies an RST opcode), in decreasing priority.
- Interrupt latency is the time from the request to the first ISR instruction. Keep ISRs short; save registers the main program uses.
Serial communication.
- UART (asynchronous): no shared clock. Each character is framed by a start bit (0), 5–9 data bits sent LSB first, an optional parity bit and 1 or 2 stop bits (1). Both ends must use the same baud rate, typically within about ±2 %. Full-duplex with separate TX and RX lines; RS-232 or RS-485 transceivers set the line levels. The common 8N1 frame is 10 bits per byte.
- SPI (synchronous): master drives SCLK, MOSI, MISO and a chip select per slave; full-duplex, simple, fast (MHz to tens of MHz), short distances. Used for ADCs, DACs and memories.
- I²C (synchronous): two open-drain lines SDA and SCL with pull-up resistors; devices addressed by 7-bit addresses on a shared bus; each byte acknowledged; half-duplex; standard 100 kbit/s, fast 400 kbit/s.
- 8051 serial port: SBUF, SCON; in mode 1 (8-bit UART) the baud rate comes from Timer 1 in mode 2.
Formulas
t_delay = (2ᵏ − N) · T_tick with T_tick = 12 / f_osc (8051) or prescaler / f_clk
- k: timer width (16 in mode 1); N: initial count.
Baud (8051 mode 1) = 2^SMOD · f_osc / (32 · 12 · (256 − TH1))
- TH1: reload value (decimal); SMOD: doubling bit in PCON.
f_PWM = f_tick / (TOP + 1) and Duty = OCR / (TOP + 1)
Characters per second = baud / bits per frame (8N1: 10 bits)
Worked examples
Example 1 (standard). Generate a 5 ms delay with an 8051 Timer 0 in mode 1 at 12 MHz. Find the initial count.
- T_tick = 12 / 12 MHz = 1 µs.
- Counts needed = 5 ms / 1 µs = 5000.
- N = 65 536 − 5000 = 60 536 = EC78H.
- Load TH0 = ECH, TL0 = 78H, set TR0 and wait for TF0.
Answer: TH0 = ECH, TL0 = 78H (ignoring the few cycles of reload overhead)
Example 2 (GATE level: UART). An 8051 with an 11.0592 MHz crystal (SMOD = 0) must send 100 bytes at 9600 baud, 8N1. Find TH1 and the time taken.
- 256 − TH1 = f_osc / (384 × baud) = 11.0592 × 10⁶ / (384 × 9600) = 3.
- TH1 = 256 − 3 = 253 = FDH.
- Each byte is 10 bits: 1 start + 8 data + 1 stop.
- Time = 100 × 10 / 9600 = 0.1042 s.
Answer: TH1 = FDH; about 104.2 ms
Example 3 (PWM). A 16 MHz microcontroller runs an 8-bit timer (TOP = 255) with prescaler 64 in fast PWM mode. Find f_PWM and the duty cycle for a compare value of 64.
- f_tick = 16 MHz / 64 = 250 kHz.
- f_PWM = 250 kHz / 256 = 976.6 Hz.
- Duty = 64 / 256 = 25 %.
Answer: 976.6 Hz, 25 % duty
Common mistakes
- Loading the timer with the count itself instead of 2ᵏ − count for an up-counter.
- Forgetting the 8051 divides the crystal by 12 before the timer.
- Computing UART throughput with 8 bits per byte instead of the full frame (start and stop bits included).
- Saying UART is half-duplex: it has separate TX and RX lines and is full-duplex.
- Long ISRs or forgetting to clear a flag that the hardware does not clear automatically, so the ISR re-enters endlessly.
For GATE IN
Expect: timer reload values for a given delay or frequency, maximum delay of a timer mode, baud-rate and transfer-time calculations, interrupt vector addresses and priority order, interrupt versus polling, and features of UART, SPI and I²C. Practise converting between counts, hex reload values and times quickly.
Quick check
- Maximum delay of an 8051 timer in mode 1 at 12 MHz?
- Tick time with an 8 MHz clock and prescaler 64?
- Which 8085 interrupt is non-maskable?
- How many wires does I²C use, excluding ground?
- At 9600 baud, 8N1, how many bytes per second?
Answers: 1. 65.536 ms 2. 8 µs 3. TRAP 4. Two 5. 960
Interview questions
All Digital Electronics and Microcontrollers interview questionsTry answering each one aloud before you open it.
1.What is a timer in the context of microcontrollers, and how does it function?Concept
A timer in microcontrollers is a hardware device that counts clock pulses. It can be used to measure time intervals, generate precise delays, or trigger events at specific intervals. Timers can operate in different modes, such as up-counting, down-counting, or up/down-counting, and can be configured to generate interrupts when they overflow or reach a certain value.
2.Explain the role of interrupts in microcontrollers.Concept
Interrupts are signals that temporarily halt the normal execution of a program to execute a special routine called an interrupt service routine (ISR). They allow microcontrollers to respond to external events or internal conditions immediately. Interrupts can be triggered by hardware events, such as a timer overflow or a pin change, or by software instructions.
3.What is serial communication, and why is it important in microcontrollers?Concept
Serial communication is a method of transmitting data one bit at a time over a communication channel. It is important in microcontrollers because it allows for communication with other devices, such as sensors, computers, or other microcontrollers, using protocols like UART, SPI, or I2C. Serial communication is often used because it requires fewer wires and can be more cost-effective than parallel communication.
4.Why are timers used in pulse-width modulation (PWM) applications?Application
Timers are used in PWM applications to generate precise timing signals that control the duty cycle of the PWM signal. By adjusting the timer's count value, the microcontroller can change the width of the pulses, which in turn controls the power delivered to a load, such as a motor or LED. This is essential for applications requiring variable speed or brightness control.
5.What happens if an interrupt is not serviced quickly enough in a microcontroller?Application
If the ISR runs late or another long ISR blocks it, events can be lost: a second edge arrives before the first is handled and only one flag is set, a UART receive buffer is overwritten (overrun), or a control loop samples late and jitters. The fix is to keep ISRs short (set a flag or copy data and leave the processing to the main loop), assign sensible priorities, and use hardware buffers or DMA for high-rate data.
6.How does a microcontroller differentiate between multiple interrupt sources?Application
A microcontroller differentiates between multiple interrupt sources using an interrupt vector table. Each interrupt source is assigned a unique vector, which points to the corresponding interrupt service routine (ISR). The microcontroller uses this table to determine which ISR to execute when an interrupt occurs. Additionally, interrupt priority levels can be set to manage which interrupts are serviced first.
7.Explain how UART works in serial communication.Concept
UART (Universal Asynchronous Receiver-Transmitter) is a hardware communication protocol that uses two wires, one for transmitting and one for receiving data. It operates asynchronously, meaning it does not require a clock signal to synchronize the data transmission. Instead, it uses start and stop bits to frame each byte of data, allowing the receiver to identify the beginning and end of each byte.
8.Calculate the time delay generated by a timer with a clock frequency of 8 MHz and a prescaler value of 64, if the timer is set to overflow at 256 counts.Numerical
- Calculate the timer tick frequency: 8 MHz / 64 = 125 kHz.
- Calculate the time for one tick: 1 / 125 kHz = 8 µs.
- Calculate the total time delay: 256 counts * 8 µs = 2048 µs or 2.048 ms.
9.What is the advantage of using SPI over UART for serial communication?Application
SPI is synchronous: the master supplies the clock, so there is no baud-rate matching and no start/stop-bit overhead, and it runs at many MHz, far faster than typical UART links. It is also simple shift-register hardware, ideal for on-board ADCs, DACs and memories. UART is also full-duplex, but it is asynchronous and point-to-point; its advantages are needing only TX and RX (no clock or chip-select lines) and working over long cables with RS-232/RS-485 transceivers, where SPI does not.
10.If a microcontroller's timer is configured with a prescaler of 256 and a clock frequency of 16 MHz, what is the frequency of the timer ticks?Numerical
- Calculate the timer tick frequency: 16 MHz / 256 = 62.5 kHz.
- Therefore, the frequency of the timer ticks is 62.5 kHz.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?