Arduion蓝牙避障智能小车代码
时间: 2023-10-25 16:06:55 浏览: 97
以下是一个简单的 Arduino 蓝牙避障智能小车代码,需要使用 HC-05 蓝牙模块:
```
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3); // 设置蓝牙模块的 RX 和 TX 引脚
int leftMotorPin1 = 9;
int leftMotorPin2 = 10;
int rightMotorPin1 = 5;
int rightMotorPin2 = 6;
int triggerPin = 7;
int echoPin = 8;
long duration, distance;
void setup() {
pinMode(leftMotorPin1, OUTPUT);
pinMode(leftMotorPin2, OUTPUT);
pinMode(rightMotorPin1, OUTPUT);
pinMode(rightMotorPin2, OUTPUT);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
BTSerial.begin(9600);
}
void loop() {
if (BTSerial.available()) {
char command = BTSerial.read();
if (command == 'F') {
forward();
}
else if (command == 'B') {
backward();
}
else if (command == 'L') {
left();
}
else if (command == 'R') {
right();
}
else if (command == 'S') {
stop();
}
}
distance = measureDistance();
if (distance < 15) {
stop();
backward();
delay(500);
left();
delay(1000);
}
}
void forward() {
digitalWrite(leftMotorPin1, HIGH);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
}
void backward() {
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, HIGH);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, HIGH);
}
void left() {
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, HIGH);
digitalWrite(rightMotorPin1, HIGH);
digitalWrite(rightMotorPin2, LOW);
}
void right() {
digitalWrite(leftMotorPin1, HIGH);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, HIGH);
}
void stop() {
digitalWrite(leftMotorPin1, LOW);
digitalWrite(leftMotorPin2, LOW);
digitalWrite(rightMotorPin1, LOW);
digitalWrite(rightMotorPin2, LOW);
}
long measureDistance() {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
return duration * 0.034 / 2;
}
```
该代码使用了 HC-SR04 超声波距离传感器和 L298N 驱动器来控制车轮。当距离传感器检测到障碍物时,车辆会向后移动并向左转。可以通过 Bluetooth 应用程序向小车发送命令,如前进、后退、左转、右转或停止。
阅读全文