arduino蓝牙小车代码
时间: 2023-09-08 07:13:14 浏览: 107
以下是一个简单的 Arduino 蓝牙小车控制代码,你需要先将蓝牙模块与 Arduino 连接,并确保你已经安装了相应的库文件。
```c++
#include <SoftwareSerial.h> //引入蓝牙库文件
SoftwareSerial BTSerial(2, 3); //定义蓝牙串口对象
int motor1Pin1 = 4; //定义电机1引脚1
int motor1Pin2 = 5; //定义电机1引脚2
int motor2Pin1 = 6; //定义电机2引脚1
int motor2Pin2 = 7; //定义电机2引脚2
void setup(){
pinMode(motor1Pin1, OUTPUT);
pinMode(motor1Pin2, OUTPUT);
pinMode(motor2Pin1, OUTPUT);
pinMode(motor2Pin2, OUTPUT);
BTSerial.begin(9600); //设置蓝牙串口通信速度为9600
}
void loop(){
if(BTSerial.available() > 0){ //当蓝牙有数据传输时
char command = BTSerial.read(); //读取蓝牙传来的数据
switch(command){
case 'F': //前进
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
break;
case 'B': //后退
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);
break;
case 'L': //左转
digitalWrite(motor1Pin1, HIGH);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, HIGH);
break;
case 'R': //右转
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, HIGH);
digitalWrite(motor2Pin1, HIGH);
digitalWrite(motor2Pin2, LOW);
break;
case 'S': //停止
digitalWrite(motor1Pin1, LOW);
digitalWrite(motor1Pin2, LOW);
digitalWrite(motor2Pin1, LOW);
digitalWrite(motor2Pin2, LOW);
break;
}
}
}
```
你可以使用串口调试助手发送 "F" 以前进,"B" 以后退,"L" 以左转,"R" 以右转,"S" 以停止小车的运动。
阅读全文