要求:依次4/5灯亮;3/6灯亮;2/7灯亮;1/8灯亮,循环反复。
接在AT89C51的P0口
#include <reg51.h>
// 定义等待时间
#define DELAY 50000
void main() {
// 定义灯的状态数组
// 初始状态为第四、五个灯亮
unsigned char lights[] = {0b11100000, 0b00110000};
while (1) {
// 依次将灯的状态输出到 P0 口
P0 = lights[0];
delay(DELAY);
P0 = lights[1];
delay(DELAY);
// 依次将灯的状态移位,实现灯的循环反复
unsigned char temp = lights[0] << 1;
lights[0] = (temp & 0b10000000) | (lights[1] >> 4);
lights[1] = (temp & 0b01110000) | (lights[1] << 1);
}
}
// 定义等待函数
void delay(unsigned int time) {
while (time--);
}
上面程序中使用了 reg51.h 头文件,包含了 C51 汇编语言的一些常用宏定义。这个程序使用了两个变量 lights[0] 和 lights[1] 来表示灯的状态。通过移位运算来改变灯的状态,实现灯的循环反复。