#include <reg51.h>sbit IN1 = P1^0;sbit IN2 = P1^1;sbit IN3 = P1^2;sbit IN4 = P1^3;sbit IR1 = P2^0;sbit IR2 = P2^1;sbit IR3 = P2^2;sbit IR4 = P2^3;sbit IR5 = P2^4;void delay(unsigned int t) //延时函数{ unsigned int i,j; for(i=0;i<t;i++) for(j=0;j<120;j++);}void forward() //小车前进{ IN1 = 1; IN2 = 0; IN3 = 1; IN4 = 0;}void back() //小车后退{ IN1 = 0; IN2 = 1; IN3 = 0; IN4 = 1;}void left() //小车左转{ IN1 = 0; IN2 = 1; IN3 = 1; IN4 = 0;}void right() //小车右转{ IN1 = 1; IN2 = 0; IN3 = 0; IN4 = 1;}void stop() //小车停止{ IN1 = 0; IN2 = 0; IN3 = 0; IN4 = 0;}void main(){ while(1) { if(IR1==0&&IR2==1&&IR3==0&&IR4==1&&IR5==0) //小车直行 { forward(); } else if(IR1==0&&IR2==1&&IR3==1&&IR4==1&&IR5==0) //小车左偏 { left(); delay(500); } else if(IR1==0&&IR2==0&&IR3==1&&IR4==0&&IR5==0) //小车右偏 { right(); delay(500); } else if(IR1==0&&IR2==0&&IR3==1&&IR4==1&&IR5==0) //小车左转 { left(); delay(1000); } else if(IR1==0&&IR2==1&&IR3==1&&IR4==0&&IR5==0) //小车右转 { right(); delay(1000); } else //小车后退 { back(); delay(500); } }}优化上述代码
时间: 2023-08-16 07:03:22 浏览: 97
1. 在定义引脚时可以直接使用宏定义,避免了在代码中多次使用硬编码。
2. 将延时函数移动到头文件中,方便代码的复用和修改。
3. 使用switch语句代替多重if-else语句,代码更加清晰易读。
下面是优化后的代码:
```
#include <reg51.h>
#include "delay.h"
#define IN1 P1^0
#define IN2 P1^1
#define IN3 P1^2
#define IN4 P1^3
#define IR1 P2^0
#define IR2 P2^1
#define IR3 P2^2
#define IR4 P2^3
#define IR5 P2^4
void forward() {
IN1 = 1;
IN2 = 0;
IN3 = 1;
IN4 = 0;
}
void back() {
IN1 = 0;
IN2 = 1;
IN3 = 0;
IN4 = 1;
}
void left() {
IN1 = 0;
IN2 = 1;
IN3 = 1;
IN4 = 0;
}
void right() {
IN1 = 1;
IN2 = 0;
IN3 = 0;
IN4 = 1;
}
void stop() {
IN1 = 0;
IN2 = 0;
IN3 = 0;
IN4 = 0;
}
void main() {
while(1) {
switch((IR1<<4)|(IR2<<3)|(IR3<<2)|(IR4<<1)|IR5) {
case 0b01010: //小车直行
forward();
break;
case 0b01110: //小车左偏
left();
delay_ms(500);
break;
case 0b00100: //小车右偏
right();
delay_ms(500);
break;
case 0b01100: //小车左转
left();
delay_ms(1000);
break;
case 0b01001: //小车右转
right();
delay_ms(1000);
break;
default: //小车后退
back();
delay_ms(500);
break;
}
}
}
```
阅读全文