On this page
Square Wave Generation using Timer
This program generates a square wave on pin P1.5 using Timer 0 for precise timing.
Description
The program uses Timer 0 in mode 1 (16-bit timer) to create accurate delays between pin toggles, generating a square wave output.
Code
| |
Explanation
Timer Configuration
- MOV TMOD, #00000001B: Configure Timer 0 in mode 1
- 16-bit timer mode
- No counter mode
- CLR P1.5: Initialize output pin to 0
Main Loop
- MOV TL0, #0FFH: Load timer low byte
- MOV TH0, #00H: Load timer high byte
- Initial count = 00FFH = 255
- CPL P1.5: Toggle the output pin
- ACALL DELAY: Wait for timer overflow
- SJMP HERE: Repeat
Delay Subroutine
- SETB TR0: Start Timer 0
- JNB TF0, NEXT: Wait for timer overflow flag
- TF0 = 1 when timer overflows from FFFF to 0000
- CLR TF0: Clear overflow flag
- RET: Return
Frequency Calculation
With 11.0592 MHz crystal:
- Machine cycle = 12/11.0592 MHz = 1.085 µs
- Timer counts from 00FFH to FFFFH = 65535 - 255 = 65280 counts
- Time per half cycle = 65280 × 1.085 µs ≈ 70.8 ms
- Full period = 141.6 ms
- Frequency ≈ 7.06 Hz
To change frequency, modify TH0 and TL0 values:
- Lower initial value → Longer delay → Lower frequency
- Higher initial value → Shorter delay → Higher frequency
Example: For higher frequency
| |