Timers in 8051 Microcontroller
Timers in 8051 Microcontroller
Timers in the 8051 microcontroller are crucial for timing operations, generating
delays, counting external events, and serving as clock sources. The 8051 has two
timers: Timer 0 and Timer 1 (some variants have Timer 2 as well). These timers can
operate as timers (incrementing based on the internal clock) or counters
(incrementing based on external events).
1. Timer Registers
The 8051 has four main registers for timers:
The TMOD (Timer Mode) register is an 8-bit register used to configure the modes
and functions of Timer 0 and Timer 1 in the 8051 microcontroller.
Example:
GATE = 1: Timer starts only when INT0 = 1 (for Timer 0) or INT1 = 1 (for Timer 1).
GATE = 0: Timer starts as soon as TR0/TR1 is set.
Example:
Mode M1 M0 Description
Mode 0 0 0 13-bit Timer (8-bit THx + 5-bit TLx)
Mode 1 0 1 16-bit Timer (THx + TLx)
Mode 2 1 0 8-bit Auto Reload (THx holds reload value)
Mode 3 1 1 Split Mode (Timer 0 acts as two 8-bit timers)
Assembly Code:
MOV TMOD, #01H ; Timer 0 in Mode 1 (16-bit)
MOV TH0, #0xFC ; Load High Byte
MOV TL0, #0x66 ; Load Low Byte
SETB TR0 ; Start Timer 0
Assembly Code:
Gate = 0 (Software-controlled)
C/T = 1 (Counter Mode)
Mode 1 (M1 = 0, M0 = 1) (16-bit Counter)
Assembly Code:
Assembly Code:
Bit 7 6 5 4 3 2 1 0
Use TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Example
Assembly Code
C Code
TMOD = 0x00; // Timer 0 Mode 0
TH0 = 0x1F; // Load High byte
TL0 = 0x00; // Load Low byte
TR0 = 1; // Start Timer
while (TF0 == 0); // Wait for overflow
TF0 = 0; // Clear overflow flag
TR0 = 0; // Stop Timer
Use Case
Example
Assembly Code
C Code
Use Case
Example
Assembly Code
C Code
Use Case
Example
Assembly Code
C Code
Use Case