Skip to main content

1 kHz square wave on P1.5 using timer

Short answer

With 11.0592 MHz, timer clock =921.6 kHz, half period 0.5 ms requires 461 counts. After compensating for instruction overhead, load TH0=FEH, TL0=3EH. Toggle P1.5 on TF0 overflow, producing approximately 1.002 kHz.

Assume that XTAL = 11.0592 MHz, write a program to generate a square wave of 1 kHz frequency on pin P1.5 of 8051 microcontroller using timer.

Calculation

XTAL = 11.0592 MHz, so the timer clock = 11.0592 MHz / 12 = 921.6 kHz and one machine cycle = 1.0851 us.

  • Frequency 1 kHz gives T = 1 ms, so each half period (high or low) = 0.5 ms.
  • Count needed = 500 us / 1.0851 us = 460.8, about 461 counts.
  • Timer 0 in mode 1 (16-bit): initial value = 65536 - 461 = 65075 = FE33H.
  • The loop instructions (reload, JNB, CLR, CPL, SJMP) add about 11 machine cycles per half period. To compensate, use 461 - 11 = 450 counts: 65536 - 450 = 65086 = FE3EH, so TH0 = FEH, TL0 = 3EH.

Program

        ORG 0000H
        MOV TMOD,#01H       ; Timer 0, mode 1 (16-bit timer)
AGAIN:  MOV TH0,#0FEH       ; 65536 - 450 = 65086 = FE3EH
        MOV TL0,#3EH
        SETB TR0            ; start Timer 0
WAIT:   JNB TF0,WAIT        ; wait until TF0 = 1 (overflow)
        CLR TR0             ; stop timer
        CLR TF0             ; clear overflow flag
        CPL P1.5            ; toggle the output pin
        SJMP AGAIN          ; repeat: half period 0.5 ms
        END

Each time Timer 0 overflows (TF0 = 1), P1.5 is complemented and the timer is reloaded, so P1.5 gives a square wave. In a simulator the half period measured 499.1 us, i.e. about 1.002 kHz.

C version

#include <reg51.h>
sbit wave = P1^5;
void main(void)
{
    TMOD = 0x01;                 /* Timer 0, mode 1 */
    while (1) {
        TH0 = 0xFE;  TL0 = 0x3E; /* 65086 */
        TR0 = 1;
        while (TF0 == 0);        /* wait for overflow */
        TR0 = 0;  TF0 = 0;
        wave = ~wave;            /* toggle P1.5 */
    }
}

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 9 questions →