We have previously successfully lit an LED on the 8051 microcontroller. But now I hope to advance a bit and light up a string of LEDs.
Create a project and burn the HEX file to the microcontroller
Please directly visit TylerHong’s tutorial.
Code Writing
#include "reg52.h"
#include "intrins.h"
typedef unsigned char u8;
typedef unsigned int u16;
#define LED_PORT P2
void delay(time) {
while (time--);
}
void main() {
u8 i = 0;
LED_PORT = ~0x01;
while (1) {
for (i = 0 ; i < 7 ; ++i) {
LED_PORT = _crol_(LED_PORT, 1);
delay(50000);
}
for (i = 0 ; i < 7 ; ++i) {
LED_PORT = _cror_(LED_PORT, 1);
delay(50000);
}
}
}
Code Explanation
#include "intrins.h"
This is a new header file we have introduced.
After we successfully compile this code, you can click the small arrow in the left file manager to open the details of this header file.
We can see two functions _crol and _cror.
These are the functions we will need to use later; one represents moving to the left, the other moving to the right.
void delay(time) {
while (time--);
}
This is the delay function. We haven’t learned about timers yet, so we’ll use this simple delay function as a substitute for now.
for (i = 0 ; i < 7 ; ++i) {
LED_PORT = _crol_(LED_PORT, 1);
delay(50000);
}
This is the main content, the for loop executes 7 times because we only need 7 changes, we have 8 lights, but the light in the initial position does not need to be changed to be lit.
_crol_(LED_PORT, 1)
This line of code means to shift the LED_PORT value one bit to the left, and the bit on the far left will be appended to the end of the entire number, so this is different from the left shift <<, which directly appends 0 at the end.
for (i = 0 ; i < 7 ; ++i) {
LED_PORT = _cror_(LED_PORT, 1);
delay(50000);
}
This section of code is the same as the above, similarly, so no further explanation is needed.
Running the Code
Once we have successfully burned the code to the microcontroller and pressed the switch, we can see the effect shown below.