#include<reg52.h> #define uchar unsigned char ; #define uint unsigned int ; Ledcode[6][8]={ {0x01,0xEF,0xEF,0xEF,0x01,0xFF,0xFF,0xFF},//H {0x83,0x7D,0x75,0x7B,0x85,0xFF,0xFF,0xFF},//Q {0x03,0xFD,0xFD,0xFD,0x03,0xFF,0xFF,0xFF},//U {0xEF,0xEF,0x01,0xEF,0xEF,0xFF,0xFF,0xFF},//+ {0x01,0xF7,0x0F,0xF7,0x01,0xFF,0xFF,0xFF},//W {0xFB,0xFD,0x7D,0x03,0x7F,0xFF,0xFF,0xFF}};//J void delayms(int n) { int i; int j; for(i=0;i<n;i++) for(j=0;j<110;j++); } void main() { int i=0; int j=0; int flag=0; int t=25; int time=0; while(1) { P0=0XFF; P1=0X00; delayms(1000); for(j=0;j<8;j++) { time=100; for(time=100;time>0;time--) { for(i=0;i<8;i++) { P0=(0X80>>i); P1 = Ledcode[j][i]; delayms(2); P0=0X00; P1=0XFF; } } } while(1) { for(i=0;i<8;i++) { if(flag==1) { for(t=25;t>0;t--) { for(j=0;j<8;j++) { P0=(0X80>>j);//ÓÒÒÆjλ P1=Ledcode[i][j]; delayms(25-t); P0=0X00; P1=0XFF; delayms(t); } } flag=0; delayms(1000); } else if(flag==0) { for(t=0;t<25;t++) { for(j=0;j<8;j++) { P0=(0X80>>j);//ÓÒÒÆjλ P1=Ledcode[i][j]; delayms(25-t); P0=0X00; P1=0XFF; delayms(t); } } flag=1; delayms(1000); } } if(i==8) { i=0; P0=0X00; P1=0XFF; break; } } } }优化一下这段代码
时间: 2023-12-03 07:03:45 浏览: 116
这段代码可以进行如下优化:
1. 在循环中使用常量的地方可以使用宏定义,例如将 `delayms(1000)` 定义为 `DELAY_1000MS`。
2. 在延时函数中可以使用定时器来进行延时,提高精度。
3. 将循环中的常量赋值移到循环外部,减少每次循环的赋值操作。
4. 在循环中使用位运算来代替移位操作,提高效率。
优化后的代码如下所示:
```
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
#define DELAY_1000MS 1000
uchar Ledcode[6][8] = {
{0x01, 0xEF, 0xEF, 0xEF, 0x01, 0xFF, 0xFF, 0xFF}, //H
{0x83, 0x7D, 0x75, 0x7B, 0x85, 0xFF, 0xFF, 0xFF}, //Q
{0x03, 0xFD, 0xFD, 0xFD, 0x03, 0xFF, 0xFF, 0xFF}, //U
{0xEF, 0xEF, 0x01, 0xEF, 0xEF, 0xFF, 0xFF, 0xFF}, //+
{0x01, 0xF7, 0x0F, 0xF7, 0x01, 0xFF, 0xFF, 0xFF}, //W
{0xFB, 0xFD, 0x7D, 0x03, 0x7F, 0xFF, 0xFF, 0xFF} //J
};
void delayms(int n) {
int i;
int j;
for (i = 0; i < n; i++) {
for (j = 0; j < 110; j++);
}
}
void main() {
int i = 0;
int j = 0;
int flag = 0;
int t = 25;
int time = 0;
P0 = 0xFF;
P1 = 0x00;
while (1) {
delayms(DELAY_1000MS);
for (j = 0; j < 8; j++) {
time = 100;
while (time-- > 0) {
for (i = 0; i < 8; i++) {
P0 = ~(0x01 << i);
P1 = Ledcode[j][i];
delayms(2);
P0 = 0x00;
P1 = 0xFF;
}
}
}
while (1) {
for (i = 0; i < 8; i++) {
if (flag == 1) {
for (t = 25; t > 0; t--) {
for (j = 0; j < 8; j++) {
P0 = ~(0x01 << j);
P1 = Ledcode[i][j];
delayms(25 - t);
P0 = 0x00;
P1 = 0xFF;
delayms(t);
}
}
flag = 0;
delayms(DELAY_1000MS);
} else if (flag == 0) {
for (t = 0; t < 25; t++) {
for (j = 0; j < 8; j++) {
P0 = ~(0x01 << j);
P1 = Ledcode[i][j];
delayms(25 - t);
P0 = 0x00;
P1 = 0xFF;
delayms(t);
}
}
flag = 1;
delayms(DELAY_1000MS);
}
}
if (i == 8) {
i = 0;
P0 = 0x00;
P1 = 0xFF;
break;
}
}
}
}
```
阅读全文