51 single chip microcomputer precise delay procedure (crystal oscillator 12MHz, a machine cycle 1us.)
Several precise delay procedures: in the calculation of accurate delay, the most easily overlooked is the calculation of the loop outside the part of the delay,
This part does not affect the program in situations where the time requirement is not high.
A. 500MS Delay subroutine program:. (Crystal oscillator 12MHz, a machine cycle of 1us.)
void delay500ms (void)
{
unsigned char i,j,k;
for (i=15;i>0;i--)
for (j=202;j>0;j--)
for (k=81;k>0;k--);
}
Calculation Analysis:
Program has a total of three layers of loops
One-layer cycle n:r5*2 = 81*2 = 162us djnz 2us
Two-layer cycle m:r6* (n+3) = 202*165 = 33330us djnz 2us + R5 Assignment 1us = 3us
Three-layer cycle: r7* (m+3) = 15*33333 = 499995us djnz 2us + R6 Assignment 1us = 3us
Outside the loop: 5us subroutine calls 2us + subroutine returns 2us + R7 Assignment 1us = 5us
Total time delay = three-layer cycle + cycle = 499995+5 = 500000us =500ms
Calculation formula: Delay Time =[(2*r5+3) *r6+3]*r7+5
Two. 200ms Delay subroutine Program:
void delay200ms (void)
{
unsigned char i,j,k;
for (i=5;i>0;i--)
for (j=132;j>0;j--)
for (k=150;k>0;k--);
}
Three. 10ms Delay subroutine Program:
void delay10ms (void)
{
unsigned char i,j,k;
for (i=5;i>0;i--)
for (j=4;j>0;j--)
for (k=248;k>0;k--);
}
four. 1s delay subroutine program:
void Delay1s (void)
{
unsigned char h,i,j,k;
for (h=5;h>0;h--)
for (i=4;i>0;i--)
for (j=116;j>0;j--)
for (k=214;k>0;k--);
}
void delay1s (void)//12m crystal oscillator, delay 999999.00us
{
unsigned char i,j,k;
for (i=46;i>0;i--)
for (j=152;j>0;j--)
for (k=70; k>0;k--);
}