8051 (AT89C51) delay function implementation using
timer0
This post provides the delay function implementation using
timer0 ( in c language ) for 8051 micro-controller ( e-g for AT89C51 or
AT89C52 etc ). Timer0 is used here to generate the exact delay required. A
function named 'delay_usec()' is implemented in the code, which produces
the delay in micro seconds (If 12Mhz crystal is used with 8051). For example,
to generate a delay of 500 usec you can call delay function as delay_usec(500);.
The code and Proteus simulation is given in the 'Downloads' section at the bottom of this page.
The result of the Proteus simulation is shown below.
The code and Proteus simulation is given in the 'Downloads' section at the bottom of this page.
The result of the Proteus simulation is shown below.
In the figure above we can see that, P2.0 pin
is changing its value after exactly 1msec. This is being done by using the
statement delay_usec(1000);.
Code
The code for the main function is shown below.
In the main code, it is clear that Out pin is
changing its state after every 1000usec (i-e 1msec). This behavior is
also shown in the Figure 1 above.
The implementation of delay function in the code is shown below.
The implementation of delay function in the code is shown below.
In the delay_usec() function,
firstly timer0 is initialized in mode 1 (16bit mode). Then appropriate value is
loaded in the timer0 registers (TH0 and TL0), to generate correct delay. After
that, timer0 interrupt and global interrupt bit is enabled. A variable
named TimeUp is used to identify when timer0 overflows
and Timer0_ISRfunction is executed. After starting timer0, code
waits for the Time Up variable to become 1, this variable is
set equal to 1 only when Timer0_ISR function executes. In the
end, timer0 is stopped using the TR0=0 statement.
This delay_usec() fucntion can generate a delay from 0 to 65535 micro seconds only. In other words, you can pass a parameter of 0 to 65535 in the argument of delay_usec() function. This means, delay usec() function can generate a maximum delay of 65.5 msec. To generate a delay higher than this value, you can call this function inside a for loop.
Downloads
The code was compiled in Keil uvision4 and simulation
was made in Proteus v7.7.
To download code and proteus simulation click here.
To download code and proteus simulation click here.
No comments:
Post a Comment