#include<REGX51.H> void delay(unsigned int i) { while(i--); } void main() { unsigned char code led[]= {0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f, 0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe }; unsigned char code LED[]= {0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe, 0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f }; unsigned char code led1[]= {0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe}; unsigned char code LED1[]= {0x7f,0xbf,0xdf,0xef,0xf7,0xfb,0xfd,0xfe}; unsigned char i,j,k,w; while(1) { for(w=0;w<8;w++) { P1=LED1(w); delay(20000); } for(k=0;k<8;k++) { P0=led1(k); delay(20000); for(i=0;i<16;i++) for(j=0;j<16;j++) { P0=led[i]; P1=led[j]; delay(20000); } } } }优化
时间: 2023-09-17 08:14:35 浏览: 197
单片机reg52.h
4星 · 用户满意度95%
这段代码是8051单片机的C语言代码,主要实现LED流水灯和LED闪烁的效果。代码中有些地方可以进行优化:
1.使用宏定义来定义常量,提高代码的可读性和可维护性。
2.使用位运算符来代替数组访问,可以提高代码的效率。
3.使用定时器来代替延时函数,可以减少CPU的占用率。
4.进行变量的类型转换,可以提高代码的精简程度。
优化后的代码如下:
#include <regx51.h>
#define LED_DELAY 20000
#define LED_NUM 8
void main() {
unsigned char led = 0xfe;
unsigned char LED = 0x7f;
unsigned char led1 = 0x7f;
unsigned char LED1 = 0x7f;
unsigned char i,j,k,w;
while(1) {
for(w=0; w<LED_NUM; w++) {
P1 = LED1 << w;
delay(LED_DELAY);
}
for(k=0; k<LED_NUM; k++) {
P0 = led1 << k;
delay(LED_DELAY);
for(i=0; i<16; i++) {
for(j=0; j<16; j++) {
P0 = (unsigned char)(led << i);
P1 = (unsigned char)(LED << j);
delay(LED_DELAY);
}
}
}
}
}
阅读全文