两个L298N控制的HC—06蓝牙避障模块小车代码
时间: 2023-06-26 15:09:36 浏览: 174
蓝牙控制小车代码
以下是一个基于两个L298N驱动器和HC-06蓝牙模块的避障小车的代码,使用Arduino IDE编写:
```
#include <SoftwareSerial.h>
// 初始化软串口,RX为11,TX为10
SoftwareSerial bluetooth(11, 10);
//定义各个引脚
const int leftMotorForward = 9;
const int leftMotorBackward = 8;
const int rightMotorForward = 7;
const int rightMotorBackward = 6;
const int trigPin = 5;
const int echoPin = 4;
//定义测距变量
long duration;
int distance;
void setup() {
//设置引脚为输出模式
pinMode(leftMotorForward, OUTPUT);
pinMode(leftMotorBackward, OUTPUT);
pinMode(rightMotorForward, OUTPUT);
pinMode(rightMotorBackward, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//设置串口速率为9600
Serial.begin(9600);
//设置蓝牙串口速率为9600
bluetooth.begin(9600);
}
void loop() {
//发射超声波
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//读取超声波返回的距离
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
//调试用,输出距离
Serial.print("Distance: ");
Serial.println(distance);
//如果距离小于20cm,后退
if (distance < 20) {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, HIGH);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, HIGH);
}
//否则向前走
else {
digitalWrite(leftMotorForward, HIGH);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, HIGH);
digitalWrite(rightMotorBackward, LOW);
}
//检查蓝牙模块是否有数据可用
if (bluetooth.available()) {
char command = bluetooth.read();
//如果收到f,前进
if (command == 'f') {
digitalWrite(leftMotorForward, HIGH);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, HIGH);
digitalWrite(rightMotorBackward, LOW);
}
//如果收到b,后退
else if (command == 'b') {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, HIGH);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, HIGH);
}
//如果收到l,左转
else if (command == 'l') {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, HIGH);
digitalWrite(rightMotorForward, HIGH);
digitalWrite(rightMotorBackward, LOW);
}
//如果收到r,右转
else if (command == 'r') {
digitalWrite(leftMotorForward, HIGH);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, HIGH);
}
//如果收到s,停止
else if (command == 's') {
digitalWrite(leftMotorForward, LOW);
digitalWrite(leftMotorBackward, LOW);
digitalWrite(rightMotorForward, LOW);
digitalWrite(rightMotorBackward, LOW);
}
}
}
```
请注意,这只是一个示例代码,并且可能需要根据您的硬件配置进行修改。此外,此代码只提供了基本的避障和控制功能,您可能需要添加更多的功能以满足您的需求。
阅读全文