51小车超声波避障代码,小车有四个电机,四个使能端,共计八个电机接口
时间: 2024-03-21 15:42:05 浏览: 19
以下是一个简单的51小车超声波避障代码示例,假设使用了L298N电机驱动模块,小车有四个电机,四个使能端,共计八个电机接口:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit enA=P1^0;
sbit in1=P1^1;
sbit in2=P1^2;
sbit enB=P1^3;
sbit in3=P1^4;
sbit in4=P1^5;
sbit trig=P3^5;
sbit echo=P3^4;
uint distance;
void delay(uint z) {
uint x,y;
for (x=z; x>0; x--)
for (y=110; y>0; y--);
}
void init() {
TMOD=0x01;
TH0=0;
TL0=0;
TR0=1;
}
void send_pulse() {
trig=1;
delay(10);
trig=0;
}
void get_distance() {
while (echo==0);
TR0=1;
while (echo==1);
TR0=0;
distance=(TH0<<8)+TL0;
distance=distance/58;
}
void forward() {
enA=1;
enB=1;
in1=1;
in2=0;
in3=1;
in4=0;
}
void backward() {
enA=1;
enB=1;
in1=0;
in2=1;
in3=0;
in4=1;
}
void left() {
enA=1;
enB=1;
in1=0;
in2=1;
in3=1;
in4=0;
}
void right() {
enA=1;
enB=1;
in1=1;
in2=0;
in3=0;
in4=1;
}
void stop() {
enA=0;
enB=0;
in1=0;
in2=0;
in3=0;
in4=0;
}
void main() {
init();
while (1) {
send_pulse();
get_distance();
if (distance<20) {
stop();
delay(500);
backward();
delay(1000);
stop();
delay(500);
left();
delay(1000);
stop();
delay(500);
}
else
forward();
}
}
```
其中,`enA`和`enB`是L298N电机驱动模块的使能端口,`in1-in4`是电机的控制端口。`trig`和`echo`是超声波模块的触发和接收端口。在主循环中,当检测到距离障碍物小于20cm时,车将停止,后退1秒钟,左转1秒钟,然后再次停止。否则,车将继续向前行驶。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)