In short
A microcontroller is its CPU plus on-chip peripherals; timers, analog-to-digital converters (ADC), pulse-width modulators (PWM) and the interrupt controller are the four that appear in almost every embedded design. Timers measure and generate time, the ADC turns sensor voltages into numbers, PWM controls motor speed, LED brightness and SMPS duty, and interrupts let the CPU respond to events without polling. These are standard units in AICTE/CBCS "Microprocessors and Microcontrollers" and "Embedded Systems" courses, carry marks in GATE EC/IN (timer count and ADC resolution numericals) and in ISRO/BARC/DRDO and PSU papers. In interviews at Bosch, Continental, L&T Technology Services, Tata Elxsi, KPIT, Wipro, HCL, Qualcomm and Texas Instruments India, duty-cycle arithmetic, ADC step size and "what must an ISR never do" are near-certain questions.
Explained
Timers and counters: the core block
- A timer is a free-running binary up-counter clocked from a known internal clock; a counter is the same hardware clocked from an external pin. The hardware is identical — only the clock source differs.
- Resolution = width of the count register: 8-bit (0-255), 16-bit (0-65,535), 32-bit (0-4,294,967,295).
- Prescaler: a divider between the clock source and the counter (÷1, 2, 4, 8, 64, 256, 1024 typical). It trades resolution for maximum delay: tick period = prescaler / f_clk.
- Overflow (rollover): when the counter crosses its maximum it wraps to 0 and sets an overflow flag (TF in 8051, TOV in AVR, UIF in STM32), which can raise an interrupt.
- Auto-reload / modulus mode: instead of wrapping at full scale, the counter resets at a programmable value in an auto-reload register (ARR in STM32, OCR0A in AVR CTC mode, TH1 in 8051 mode 2). This gives exact periodic interrupts with no software reload error.
- Up / down / centre-aligned (up-down) counting: centre-aligned counting is used for motor-control PWM because it keeps the pulse centred and reduces harmonic content.
- Modes in the 8051 Timer 0/1 (classic exam content): Mode 0 = 13-bit, Mode 1 = 16-bit (software must reload), Mode 2 = 8-bit auto-reload (used to set UART baud rate), Mode 3 = Timer 0 split into two 8-bit timers. Controlled by TMOD (mode/gate/C-T bits) and TCON (run bits TR0/TR1 and flags TF0/TF1).
- Input capture: an edge on a pin copies the running counter into a capture register and flags an interrupt — used to measure pulse width, period, frequency, duty cycle, and to read ultrasonic (HC-SR04) or tachometer signals.
- Output compare: when the counter equals a compare register, a pin toggles/sets/clears and/or an interrupt fires — the basis of waveform generation and of software timer ticks.
- Watchdog timer (WDT): an independent timer that resets the chip if software does not "kick"/refresh it in time; mandatory in safety-related designs (ISO 26262 automotive, IEC 61508 industrial).
- Real-time clock (RTC): a low-power counter on a 32.768 kHz crystal (215 Hz, so a 15-bit prescaler gives exactly 1 Hz) keeping calendar time in standby.
- SysTick in ARM Cortex-M: a dedicated 24-bit down-counter reserved for the OS tick (typically 1 ms).
Analog-to-digital converter (ADC)
- Converts an analog input voltage into an n-bit code by comparing it against a reference V_ref. Output code is proportional to V_in/V_ref — so V_ref accuracy directly limits measurement accuracy.
- Resolution n = number of output bits; number of levels = 2n; step size (1 LSB) = V_ref / 2n (unipolar, full-scale = V_ref). Many texts use V_ref/(2n − 1) when full scale is defined as the last code; state the convention used.
- Quantisation error = ±½ LSB; maximum SNR for an ideal ADC = 6.02n + 1.76 dB. ENOB (effective number of bits) is the real resolution after noise and distortion.
- Types:
- Successive approximation register (SAR) — the standard on-chip type (8051 derivatives, AVR, PIC, STM32). A binary search sets each bit from MSB down; n bits need n clock cycles. Medium speed (ksps to a few Msps), 8-16 bit, low power.
- Flash (parallel) — 2n − 1 comparators, one clock cycle, fastest but area- and power-hungry; used in GHz-class converters.
- Dual-slope (integrating) — integrates input then reference; very high noise rejection and can be made to reject 50 Hz mains, slow; used in digital multimeters.
- Sigma-delta (ΣΔ) — oversampling plus noise shaping and a digital filter; 16-24 bit, slow to medium; used in weighing scales, energy meters, audio.
- Signal chain: sensor → anti-aliasing low-pass filter → amplifier/level shift → sample-and-hold (S/H) → ADC → result register. The S/H holds the input constant during conversion; acquisition time is the time the internal sampling capacitor needs to charge, and it rises with source impedance (AVR/STM32 datasheets recommend source impedance of roughly 10 kΩ or less for fast channels).
- Nyquist–Shannon sampling theorem: f_s > 2 f_max, else aliasing folds high-frequency content into the band; the anti-aliasing filter is analog and cannot be replaced by software.
- Conversion time = (cycles per conversion) × ADC clock period; throughput = 1/(acquisition + conversion). Typical AVR: 13 ADC clocks per conversion with the ADC clock kept at 50-200 kHz for full 10-bit accuracy.
- Multiplexing: one ADC core with an analog MUX scans several channels in sequence; channel crosstalk and insufficient settling after the MUX switch are common real faults.
- Trigger sources: software start, timer compare event (for exactly periodic sampling), or external pin. Results are often moved by DMA into a buffer so the CPU is not interrupted per sample.
- Errors: offset, gain, differential non-linearity (DNL — code width error; DNL = −1 LSB means a missing code), integral non-linearity (INL), and noise. Single-ended vs differential inputs: differential rejects common-mode noise on long sensor cables.
PWM: generation and use
- PWM keeps a fixed period T and varies the ON time t_on. Duty cycle D = t_on/T (×100 for %); average output = D × V_supply for a square wave switching between 0 and V_supply.
- Generated by a timer plus a compare register: the counter runs 0 → ARR (period), and the output is high while counter < CCR (compare) in up-counting edge-aligned mode.
- PWM resolution = log2(timer top value + 1); it falls as PWM frequency rises for a fixed timer clock: achievable steps = f_timer / f_PWM.
- Modes: fast PWM (edge-aligned, maximum frequency), phase-correct / centre-aligned (counter counts up then down — pulse centred, better for motors and inverters), and complementary PWM with dead-time insertion plus a break/emergency stop input on advanced timers (STM32 TIM1/TIM8) for half-bridge and three-phase inverter drive.
- Dead time is the deliberate gap between turning one transistor off and the other on in a half bridge, preventing shoot-through; typically a few hundred nanoseconds to a few microseconds.
- Applications of duty control: DC motor speed (with an H-bridge), LED dimming, servo control (20 ms period, 1-2 ms pulse), buck/boost SMPS, heater control, class-D audio, and a simple DAC when followed by an RC low-pass filter.
- Choosing frequency: above ~20 kHz for motors and lamps to stay out of the audible band; high enough for LEDs (≥ 200 Hz, usually 1 kHz+) to avoid visible flicker; low (a few Hz) for heaters and SSR control. Higher frequency means greater switching losses.
- PWM vs DAC: PWM is a one-pin digital output, cheap and lossless when driving a switch; a true DAC gives a clean analog voltage without ripple. PWM + RC filter is an inexpensive DAC whose ripple falls as the RC time constant grows (at the cost of slower response).
Interrupts
- An interrupt is a hardware or software event that makes the CPU suspend the main program, save context, execute an interrupt service routine (ISR) found via the interrupt vector table, and resume.
- Polling vs interrupt: polling wastes CPU and has response time set by the loop period; interrupts respond in microseconds and let the CPU sleep — essential for battery-powered designs.
- Sequence on an event: 1) peripheral sets its flag; 2) if the peripheral enable bit AND the global enable bit are set, the request reaches the controller; 3) CPU finishes the current instruction; 4) PC (and on Cortex-M, R0-R3, R12, LR, PC, xPSR) is pushed to the stack; 5) PC loads the vector address; 6) ISR runs; 7) return-from-interrupt restores context.
- Classification: hardware vs software (SWI/SVC); maskable vs non-maskable (NMI); internal (peripheral) vs external (pin); vectored vs non-vectored; edge-triggered vs level-triggered.
- Priority and nesting: a fixed priority order (8051: INT0 > TF0 > INT1 > TF1 > RI/TI, with IP allowing two levels) or programmable priorities. In ARM Cortex-M, the NVIC supports up to 240 interrupt lines, programmable priority (fewer bits implemented on small parts — commonly 3 or 4, so 8 or 16 levels), automatic nesting of higher-priority interrupts, tail-chaining and late arrival to cut overhead, and a 12-cycle typical latency.
- Interrupt latency = time from event to first ISR instruction; depends on the longest uninterruptible instruction, how long interrupts are disabled in critical sections, and higher-priority ISRs already running. Jitter is the variation in latency, and it matters more than latency itself in control loops.
- ISR rules: keep it short; do not call blocking or long library functions (no printf, no delay loops, no dynamic allocation); clear the interrupt flag (on many parts by writing 1 to the flag bit); mark shared variables volatile; guard multi-byte shared data with a critical section because a 16-bit variable is not read atomically on an 8-bit MCU; pass work to the main loop via a flag or queue (the "deferred processing" / bottom-half pattern).
- Re-entrancy and priority inversion are the two classic bugs; disabling interrupts is the simplest mutual exclusion on a bare-metal MCU but it must be for a handful of instructions only.
- Interrupts and low power: the CPU executes a sleep/WFI instruction and an interrupt (timer, RTC, pin change, ADC-ready) wakes it — the standard architecture for IoT nodes and battery meters.
- Flag handling faults: a flag not cleared causes the ISR to re-enter endlessly; clearing it after re-enabling can lose a second event.
Putting them together — a typical measurement loop
- Configure a timer for an exact period (prescaler + auto-reload).
- Let the timer trigger the ADC so samples are equally spaced (software triggering adds jitter).
- ADC end-of-conversion raises an interrupt or triggers DMA into a circular buffer.
- The control law (PID, filter, averaging) runs in the main loop or an RTOS task.
- The output is written to a PWM compare register, updated at a preload/shadow register boundary so the duty never changes mid-pulse (glitch-free update).
- Typical Indian lab boards for this: 8051/AT89S52 kits, Arduino Uno (ATmega328P), STM32 "Blue Pill" (STM32F103), ESP32, TI LaunchPad (MSP430/C2000) and NXP/Infineon automotive parts in industry.
Key points
- Timer vs counter - same counter hardware; a timer counts an internal clock, a counter counts external pin events.
- Prescaler - divides the clock before the counter: longer maximum interval, coarser resolution.
- Tick period - prescaler ÷ f_clock; every timer numerical starts here.
- Auto-reload - hardware reloads the count at overflow, giving jitter-free periodic interrupts; 8051 Mode 2 is the classic case.
- Input capture - latches the counter on an edge; used to measure period, frequency, pulse width and duty cycle.
- Output compare - matches the counter against a register to toggle a pin or raise an interrupt; the basis of PWM.
- Watchdog - resets the MCU if software stops kicking it; must never be kicked from inside a timer ISR alone.
- ADC step size (1 LSB) - V_ref/2n; halving the step needs one more bit.
- Quantisation error - inherent ±½ LSB; ideal SNR = 6.02n + 1.76 dB.
- SAR ADC - binary search, n clocks for n bits; the usual on-chip converter.
- Sampling theorem - f_s > 2 f_max, with an analog anti-aliasing filter ahead of the ADC.
- Duty cycle - D = t_on/T; average voltage = D × V_supply for a 0-to-V_supply square wave.
- PWM resolution - steps = f_timer/f_PWM; raising PWM frequency costs resolution.
- Dead time - gap between complementary switches to prevent shoot-through in a half bridge.
- Interrupt latency and jitter - latency is the delay to the first ISR instruction; jitter (its variation) usually hurts control loops more.
- ISR discipline - short, non-blocking, flag cleared, shared variables volatile, heavy work deferred to the main loop.
- NVIC - ARM Cortex-M controller with programmable priorities, automatic nesting and tail-chaining.
- Vector table - fixed table of ISR addresses the CPU jumps through; relocatable on Cortex-M via VTOR.
Formulas and examples
Overflow / period time: T_ov = (TOP + 1 − initial count) × t_tick (TOP = 2n − 1 for a free-running n-bit timer)
Required count for a delay: count = T_desired × f_clk / N_pre ; reload value (up-counter) = 2n − count
Auto-reload (ARR) for a period: ARR = f_clk /(N_pre × f_desired) − 1
ADC step size: ΔV = V_ref / 2n (volts per LSB); digital output D = round(V_in × 2n / V_ref)
Resolved voltage: V_in ≈ D × V_ref / 2n ; quantisation error = ±ΔV/2
Ideal SNR (dB) = 6.02 n + 1.76 ; Nyquist: f_s > 2 f_max
ADC conversion time: t_conv = (clocks per conversion) / f_ADC
Duty cycle: D = t_on/T (×100 for %) ; V_avg = D × V_supply ; f_PWM = 1/T
PWM compare value (edge-aligned, up-counting): CCR = D × (ARR + 1)
PWM steps available: N_steps = f_timer / f_PWM ; PWM resolution in bits = log2(N_steps)
Frequency measured by input capture: f_in = f_timer / (N_pre × Δcount), Δcount = capture2 − capture1
Example 1 — 8051 timer delay (16-bit, Mode 1). Crystal 11.0592 MHz; the 8051 machine cycle is 12 oscillator periods, so the timer clock is 11.0592/12 = 0.9216 MHz and one tick = 1/0.9216 MHz ≈ 1.085 µs. For a 50 ms delay: count = 50 ms / 1.085 µs ≈ 46,080 ticks. Reload value = 65,536 − 46,080 = 19,456 = 4C00H, so TH0 = 4CH, TL0 = 00H. Maximum single delay with this crystal = 65,536 × 1.085 µs ≈ 71.1 ms, so a 1-second delay needs 20 such interrupts counted in software.
Example 2 — STM32/AVR style auto-reload for an exact 1 kHz tick. Timer clock 72 MHz, prescaler N_pre = 72 (PSC register = 71) → counter clock = 1 MHz. ARR = 1,000,000/1,000 − 1 = 999. Period = (999 + 1)/1 MHz = 1.000 ms exactly, with no software reload and therefore no jitter.
Example 3 — ADC resolution and code. A 10-bit SAR ADC with V_ref = 5.00 V.
- Levels = 210 = 1,024; step size ΔV = 5.00/1024 = 4.883 mV per LSB; quantisation error = ±2.44 mV.
- An LM35 at 27.0 °C gives 10 mV/°C → V_in = 0.270 V. D = 0.270 × 1024/5.00 = 55.296 → stored code 55; recovered voltage = 55 × 4.883 mV = 268.6 mV → 26.86 °C, an error of 0.14 °C caused purely by quantisation.
- With a 2.56 V internal reference instead: ΔV = 2.56/1024 = 2.50 mV, D = 0.270/0.0025 = 108, recovered = 270.0 mV = 27.00 °C. Lowering V_ref to match the signal range roughly doubled the accuracy — a standard exam and design point.
- Ideal SNR at 10 bits = 6.02 × 10 + 1.76 = 61.96 dB.
- Conversion time at f_ADC = 125 kHz with 13 clocks = 13/125,000 = 104 µs, i.e. about 9,615 samples/s maximum.
Example 4 — PWM for DC motor speed. ATmega328P style: f_timer = 16 MHz, 8-bit fast PWM with prescaler 64.
- f_PWM = 16,000,000/(64 × 256) = 976.6 Hz.
- For 60% duty, OCR = 0.60 × 256 = 153.6 → 154, giving actual duty = 154/256 = 60.16%.
- With a 12 V supply, V_avg = 0.6016 × 12 = 7.22 V across the motor.
- If instead 20 kHz is required (above audio) from the same 16 MHz with prescaler 1: available steps = 16,000,000/20,000 = 800, i.e. log2(800) ≈ 9.6 bits — fine on a 16-bit timer with ARR = 799, impossible on an 8-bit timer, which is why motor control uses 16-bit timers.
Example 5 — Input capture frequency measurement. Timer clock 72 MHz, prescaler 72 → 1 MHz capture clock (1 µs per tick). Two successive rising edges are captured at 1,200 and 21,200. Δcount = 20,000 ticks = 20,000 µs = 20 ms → f_in = 50 Hz (a mains zero-cross signal). If the third capture reads 41,150, the second period is 19,950 µs → 50.125 Hz, so the measurement resolution here is about 1 µs in 20 ms ≈ 0.005%.
| Peripheral feature | 8051 (AT89S52) | AVR (ATmega328P) | ARM Cortex-M (STM32F103) |
|---|---|---|---|
| Timers | 2-3 × 16-bit, 4 modes | 2 × 8-bit, 1 × 16-bit | Several 16-bit, advanced + SysTick |
| Clock division | Fixed ÷12 (÷6 in some variants) | Prescaler ÷1 to ÷1024 | PSC 16-bit (÷1 to ÷65,536) |
| On-chip ADC | None in the classic 8051 | 10-bit, 8 ch, SAR | 12-bit, up to 3 units, SAR, DMA |
| PWM | Software / timer toggling | 6 hardware PWM channels | Many channels + dead-time + break |
| Interrupts | 5-6 sources, 2 priority levels | ~26 vectors, fixed priority | NVIC, up to 240 lines, nested priorities |
| DMA | No | No | Yes (ADC, timer, UART) |
| ADC type | Speed | Resolution | Typical use |
|---|---|---|---|
| Flash | Very high (one clock) | 6-8 bit | RF, oscilloscopes |
| SAR | Medium-high | 8-16 bit | On-chip MCU ADC, sensors |
| Dual slope | Low | 12-20 bit | Multimeters, panel meters |
| Sigma-delta | Low-medium | 16-24 bit | Weigh scales, energy meters, audio |
Where it is used
- Automotive electronics (Bosch, Continental, Visteon, Tata Elxsi, KPIT, L&T Technology Services, Pune/Bengaluru/Chennai): engine and motor control using centre-aligned PWM with dead time, timer-triggered ADC sampling of current sensors, and ISO 26262 watchdog and interrupt-timing requirements.
- Power electronics and drives (ABB India, Danfoss, Amara Raja, Exicom, Delta Electronics India): SMPS, solar inverters and EV motor controllers where PWM frequency, dead time and ADC synchronisation to the PWM peak decide efficiency and safety.
- Smart meters and IoT nodes (Secure Meters, Genus, HPL, L&T Metering): sigma-delta ADCs for energy measurement, RTC on a 32.768 kHz crystal, and interrupt-driven wake-from-sleep for years of battery life; meters follow IS 16444 / IS 15959 for smart metering in India.
- Medical and instrumentation (Philips India, Siemens Healthineers Bengaluru, startups): multi-channel ADC acquisition of ECG and SpO2 signals with anti-alias filtering and timer-triggered sampling.
- Consumer and appliance control (Havells, Voltas, Blue Star, Whirlpool India BLDC appliances): PWM fan/compressor speed control, NTC temperature sensing via ADC, capacitive touch using timer capture.
- Job roles: embedded firmware engineer, board bring-up engineer, BSP/driver developer, test-and-validation engineer — nearly all campus embedded interviews start from timer, ADC and interrupt configuration questions.
Interview questions
- Q: What is the difference between a timer and a counter in a microcontroller? A: The hardware counter is the same; a timer increments from a known internal clock to measure time, while a counter increments on external pulses applied to a pin to count events.
- Q: Why use a prescaler? A: It divides the clock so the same counter can measure much longer intervals, at the cost of coarser time resolution per tick.
- Q: How do you get an exact 1 ms periodic interrupt? A: Use auto-reload/CTC mode — set prescaler and reload value so the counter period is exactly 1 ms; software reloading in the ISR adds latency-dependent jitter.
- Q: What is the resolution and step size of a 12-bit ADC with a 3.3 V reference? A: 4,096 levels and 3.3/4096 ≈ 0.806 mV per LSB, with quantisation error of about ±0.4 mV.
- Q: Why can software not replace the anti-aliasing filter? A: Aliasing folds out-of-band energy into the signal band at the moment of sampling; once aliased, the content is indistinguishable from real signal and cannot be removed digitally.
- Q: Why does a SAR ADC need n clock cycles for n bits? A: It performs a binary search, resolving one bit per cycle by comparing the input against a DAC output and keeping or discarding that bit.
- Q: How do you change PWM duty cycle without changing frequency? A: Write a new value to the compare register only — the period register (ARR/TOP) sets frequency; use preload/shadow registers so the change takes effect at the next period boundary.
- Q: What decides PWM resolution? A: The ratio of timer clock to PWM frequency: steps = f_timer/f_PWM, so raising the PWM frequency with a fixed clock loses resolution.
- Q: Why is dead time inserted in complementary PWM? A: To make sure the high-side device is fully off before the low-side turns on, preventing shoot-through current that would destroy the half bridge.
- Q: What must you never do inside an ISR? A: Block or wait — no delay loops, printf, dynamic allocation, or long computation; the ISR should clear the flag, grab the data, set a flag or queue the work, and return.
- Q: Why is the keyword volatile needed for variables shared with an ISR? A: It stops the compiler from caching the value in a register or optimising the access away, forcing a fresh read from memory each time.
- Q: What is interrupt latency and what increases it? A: The delay from the event to the first ISR instruction; it grows with long uninterruptible instructions, long critical sections with interrupts disabled, context-save time, and higher-priority ISRs already executing.
- Q: What is tail-chaining in the NVIC? A: When one interrupt is pending as another finishes, Cortex-M skips the stack pop and re-push and goes straight into the next ISR, saving around a dozen cycles.
Common mistakes
- Forgetting the 8051's ÷12 machine cycle and using the crystal frequency directly as the timer clock — every delay comes out 12× wrong.
- Computing a reload value as the required count instead of 2n − count for an up-counting timer, or being off by one with ARR (the period is ARR + 1 ticks).
- Using V_ref/(2n − 1) and V_ref/2n interchangeably without stating the convention, and ignoring that V_ref accuracy and noise bound the real accuracy regardless of bit count.
- Driving the ADC input from a high-impedance source or skipping acquisition time, so the sampling capacitor never fully charges and readings sag or show crosstalk between channels.
- Sampling faster "to be safe" without an analog anti-aliasing filter, then blaming the ADC for noise that is actually aliased.
- Writing long code, delays or printf inside an ISR, not clearing the interrupt flag (endless re-entry), or forgetting volatile and critical sections around multi-byte shared variables.
- Assuming PWM gives a true analog output — without an RC filter it is a switching waveform, and its average only equals D × V_supply for an ideal 0-to-V_supply rail.
- Choosing an audible PWM frequency (a few hundred Hz) for motors or transformers, then getting a whining prototype.
Related topics
8051 microcontroller · ARM and embedded C · Embedded interfaces: UART, SPI and I2C · Sensors and actuators for embedded systems · Real-time operating systems · Internet of Things basics