84.2k views
5 votes
Write a delay routine for 8051 to create a delay of approximately 1 ms.

User DParry
by
8.2k points

1 Answer

6 votes

Final answer:

A 1 ms delay routine for an 8051 microcontroller can be implemented using a simple loop in assembly language, considering the frequency of the crystal oscillator for accurate timing.

Step-by-step explanation:

To create a delay routine of approximately 1 ms for an 8051 microcontroller, you must consider the frequency of the crystal oscillator connected to the 8051 to accurately calculate the time delay. The internal timer of the microcontroller can be used to generate this delay. Below is an example of a delay routine assuming a 12 MHz crystal is used, where each machine cycle is 1/12 of the oscillator frequency.

The code:

DELAY_1MS: MOV R2, #250; // Load loop counter
AGAIN: NOP; // No operation
NOP; // No operation
DJNZ R2, AGAIN; // Decrement R2 and jump if not zero
RET; // Return from subroutine

This code represents a simple loop that runs 250 times. Each iteration of the loop, including the DJNZ instruction, takes 4 machine cycles. Therefore, the entire loop runs for 1000 machine cycles, which corresponds to roughly 1 millisecond if a 12 MHz crystal is used (assuming no other interrupts or processes taking place).

User Stephen Lin
by
7.9k points