arduino蓝牙小车的实现
材料:
- arduino uno 开发板
- 蓝牙JDY-32
- 四驱小车套件
- 杜邦线若干
- 3.7v电池两节
软件:
-
arduino IDE 开发平台
-
移动app—-SPP(找了很多款,都搜索不到蓝牙,发现这款还好,一下子就连上了蓝牙)
相关程序:
注:代码来源为引用相关博客加以修改和优化(pwm调速),以实现小车的控制。
在调试的过程中,也存在一些问题,比如小车的左右转有一些bug.
#define STOP 0
#define FORWARD 1
#define BACKWARD 2
#define TURNLEFT 3
#define TURNRIGHT 4
int leftMotor1 = 5;
int leftMotor2 = 6;
int rightMotor1 = 9;
int rightMotor2 = 10;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);//波特率9600
pinMode(leftMotor1, OUTPUT);
pinMode(leftMotor2, OUTPUT);
pinMode(rightMotor1, OUTPUT);
pinMode(rightMotor2, OUTPUT);
}
void loop()
{
if(Serial.available()>0)//判断串口是否有数据
{
char cmd = Serial.read();//读取蓝牙模块发送到串口的数据
motorRun(cmd);//调用小车电机函数
}
}
void motorRun(int cmd)
{
switch(cmd){
case'F':
Serial.println("前进"); //输出状态
analogWrite(leftMotor1,100);
analogWrite(leftMotor2,0);
analogWrite(rightMotor1,100);
analogWrite(rightMotor2,0);
delay(500);
Stop();
break;
case'B':
Serial.println("后退"); //
analogWrite(leftMotor1,0);
analogWrite(leftMotor2,100);
analogWrite(rightMotor1,0);
analogWrite(rightMotor2,100);
delay(500);
Stop();
break;
case 'L':
Serial.println("左转"); //
analogWrite(leftMotor1, 100);
analogWrite(leftMotor2,200);
analogWrite(rightMotor1, 200);
analogWrite(rightMotor2, 100);
delay(500);
Stop();
break;
case 'l': //原地左转
analogWrite(leftMotor1,0);
analogWrite(leftMotor2,200);
analogWrite(rightMotor1,200);
analogWrite(rightMotor2,0);
Serial.println("右转");
delay(500);
Stop();
break;
case 'R':
Serial.println("右转"); //
analogWrite(leftMotor1, 200);
analogWrite(leftMotor2, 100);
analogWrite(rightMotor1, 100);
analogWrite(rightMotor2, 200);
delay(500);
Stop();
break;
case 'r': //原地右转
analogWrite(leftMotor1,200);
analogWrite(leftMotor2,0);
analogWrite(rightMotor1,0);
analogWrite(rightMotor2,200);
delay(500);
Stop();
break;
default:
}
}
void Stop(void)
{
analogWrite(leftMotor1,0);
analogWrite(leftMotor2,0); //左轮静止不动
analogWrite(rightMotor1,0);
analogWrite(rightMotor2,0); //右轮静止不动
delay(100);
}
版权声明:本文为m0_67069564原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。