3. Explain the timer/counter modes of 8051 with programming examples.


8051 Timers

Timers are digital counters incremented by pulses. They are controlled by four SFRs: TMOD, TCON, TH0/TL0, and TH1/TL1.

Timers overflow when they reach their maximum value and reset to 0. Overflow sets bits in the TCON SFR, which can be programmed to generate an interrupt and execute a subroutine.

Timer Operation Types

  • Timing operation: Timer registers incremented by internal clock pulses.
  • Counting operation: Timer registers incremented by external pulses via P3.4 (T0) for Timer 0 and P3.5 (T1) for Timer 1.

Operating Modes of 8051

TxM1 TxM0 Timer Mode Description
0 0 Mode 0 13-bit timer
0 1 Mode 1 16-bit timer
1 0 Mode 2 8-bit auto reload
1 1 Mode 3 Split timer mode




Mode 0 – 13-bit Timer Mode

  • Uses 13 bits out of 16 (5 bits from TL0/TL1, 8 bits from TH0/TH1).
  • TL0/TL1 counts 0–31; on overflow increments TH0/TH1.
  • Maximum count: 8192 values (0–8191).
  • Works as timer (internal clock) or counter (external clock).
  • Selection by D2 (Timer 0) and D6 (Timer 1) bits of TMOD.
  • Run control: D4 and D6 of TCON.
  • GATE bits (D4 and D7) in TMOD allow external control via INT0/INT1.
  • Overflow sets TF1 (Timer 1) or TF0 (Timer 0).

Mode 1 – 16-bit Timer Mode

  • Full 16-bit use: TL0/TL1 counts 0–255; overflow increments TH0/TH1.
  • Maximum count: 65536 values (0–65535).
  • Gating and run control same as Mode 0.

Mode 2 – 8-bit Auto Reload Mode

  • TL0/TL1 is incremented; on overflow, TLx is reloaded from THx automatically.
  • THx value is constant; TLx is incremented repeatedly.
  • Commonly used for baud rate generation in serial communication.
  • Gating and run control same as Mode 0.

Example:
If TH0 = FDh, TL0 = FEh → next pulse TL0 = FFh → overflow → TL0 reloaded with FDh.


Mode 3 – Split Timer Mode

  • Applicable only to Timer 0.
  • Splits Timer 0 into two independent 8-bit timers: TL0 and TH0.
  • TL0 counts 0–255; TH0 counts 0–255.
  • Real Timer 1 (TH1/TL1) stops and holds count (TR1=0 condition).
  • Used when two timers + baud rate generator are needed.

Timer Control and Operation

For timer mode (C/T=0 in TMOD):

  • Timer counts FOSC/12 rate.
  • Example: If clock = 11.059 MHz → increment rate = 921,583 Hz.
  • Delay calculation: For 0.1 sec delay → count value = 0.1 × 921,583 = 92,158.

Steps to Initialize and Use Timer in 8051

  1. Select timer mode (0–3).
  2. Initialize TMOD SFR.
  3. Load initial value into timer registers.
  4. Start timer by setting TR0/TR1 bit in TCON.
  5. Check TF0/TF1 or handle overflow via interrupt.

Bit Setting Example

To set TR1 (TCON D6):

  • MOV TCON, #40h
  • Or use bit-addressable instruction: SETB TR1 (recommended, no effect on other bits).