- 2071 Magh · 4 marks
Precise 5 ms delay in 8051
Short answer
At 12 MHz, 1 machine cycle = 1 µs, so 5 ms needs 5000 cycles. Load R7=15, R6=165; inner loop DJNZ takes 2 cycles. Total cycles = 2+1+15×(1+165×2+2)+2 =5000, yielding exactly 5 ms delay.
Write a short program in assembly language that computes a precise 5-millisecond delay using the 8051 microcontroller.
Assume a 12 MHz crystal, so one machine cycle = 1 us and 5 ms = 5000 machine cycles. The delay is made with two nested DJNZ loops, with the count chosen so that the total, including the call and return, is exactly 5000 cycles.
Calculation
- ACALL = 2 cycles, RET = 2 cycles,
MOV R7,#15= 1 cycle. - Each outer pass:
MOV R6,#165(1) + inner loop 165 xDJNZ(2 each = 330) + outerDJNZ R7(2) = 333 cycles. - 15 passes = 4995 cycles. Total = 2 + 1 + 4995 + 2 = 5000 cycles = 5.000 ms.
ORG 0000H
MAIN: ACALL DELAY5MS
SJMP MAIN
; 5 ms delay at XTAL = 12 MHz (machine cycle = 1 us)
; cycles = ACALL 2 + MOV 1 + 15 x (MOV 1 + DJNZ 165 x 2 + DJNZ 2) + RET 2 = 5000
DELAY5MS: MOV R7,#15
OUTER: MOV R6,#165
INNER: DJNZ R6,INNER
DJNZ R7,OUTER
RET
END
In a simulator at 12 MHz the call measured exactly 5.000 ms.
Alternative using Timer 0
DELAY5T: MOV TMOD,#01H ; Timer 0, mode 1
MOV TH0,#0ECH ; 65536 - 5000 = 60536 = EC78H
MOV TL0,#78H
SETB TR0 ; start the timer
WAIT: JNB TF0,WAIT ; wait for overflow
CLR TR0 ; stop timer
CLR TF0 ; clear flag
RET
This takes about 5.013 ms because of the few setup instructions; load 65536 - 5000 + 13 to compensate if it must be exact.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Microcontroller vs microprocessor; 8051 features · Embedded System, chapter 9 · asked 2×
- Microprocessor vs microcontroller; 8051 addressing · Embedded System, chapter 9
- 8051 minimum circuit and 75% duty pulse · Embedded System, chapter 9
- Addressing modes of 8051 · Embedded System, chapter 9 · asked 4×
- Why 8051 / its operational features · Embedded System, chapter 9 · asked 2×
- Purpose of port 3 and port 2 of 8051 · Embedded System, chapter 9 · asked 2×
- 8086 assembly language operators · Microprocessor, chapter 3 · asked 3×
- Assembly line balancing with cycle time · Industrial Engineering and Management, chapter 2
- Program for RK-4 first order IVP · Numerical Method, chapter 6
- Correct program: character arrays · Computer Programming, chapter 7