6.0 Timers, Counters, and Interrupts
6.1 Timers vs. Counters
| Feature | Timer | Counter |
| Function | Measures time intervals by generating delays. | Counts the number of times an external event or process occurs. |
| Clock Source | Incremented every machine cycle (internal clock). | Incremented on a 1-to-0 transition at an external input pin (T0, T1). |
| Max Count Rate | 1/12th of the oscillator frequency. | 1/24th of the oscillator frequency. |
6.2 8051 Timers: Modes and Configuration
The 8051 has two 16-bit timers, Timer 0 and Timer 1. Each is accessed via two 8-bit registers (e.g., TH0 and TL0 for Timer 0). Their operation is configured via the 8-bit TMOD (Timer Mode) register.
TMOD Register Bits (per timer):
- GATE: When set, the timer only runs while the corresponding INTx pin is high.
- C/T: Selects Timer (0) or Counter (1) mode.
- M1, M0: Selects the operational mode.
Timer Modes:
- Mode 0 (13-bit Timer): Operates as an 8-bit counter with a prescaler.
- Mode 1 (16-bit Timer): A commonly used full 16-bit timer mode.
- Mode 2 (8-bit Auto-Reload): An 8-bit timer (TLx) that automatically reloads its value from THx upon overflow. Ideal for generating fixed-period events like baud rates.
- Mode 3 (Split Timer Mode): Splits Timer 0 into two independent 8-bit timers (TL0 and TH0).
6.3 Interrupt Handling
An interrupt is a signal indicating an event that needs immediate attention, causing the processor to pause its current task and execute an Interrupt Service Routine (ISR). This avoids inefficient continuous monitoring (polling).
Interrupt Vector Table: The 8051 has six interrupt sources, each with a fixed address in ROM where the processor looks for the start of the ISR.
| Interrupt | ROM Location (Hex) |
| Reset | 0000H |
| External Hardware Interrupt 0 (INT0) | 0003H |
| Timer 0 Overflow (TF0) | 000B |
| External Hardware Interrupt 1 (INT1) | 0013H |
| Timer 1 Overflow (TF1) | 001BH |
| Serial COM (RI and TI) | 0023H |
Enabling and Priority:
- Interrupt Enable (IE) Register: A bit-addressable SFR used to enable or disable individual interrupts. The global enable bit (EA) must be set for any interrupt to be processed.
- Interrupt Priority (IP) Register: Allows each interrupt to be assigned one of two priority levels (high or low). A high-priority interrupt can interrupt a low-priority ISR in progress.