首页 > 其他 > 详细

Arduino使用HC05蓝牙模块控制小车

时间:2021-02-15 09:51:58      阅读:40      评论:0      收藏:0      [点我收藏+]

 Arduino与HC05、小车接线:

Arduino 5V - VCC
Arduino GND - GND
Arduino Pin10 - TXD
Arduino Pin11 - RXD

Arduino Pin48 - IN1

Arduino Pin46 - IN2

Arduino Pin40 - IN3

Arduino Pin48 - IN4

Arduino Pin2 - ENA

Arduino Pin3 - ENB

代码如下:

#include<SoftwareSerial.h>
SoftwareSerial mySerial(10,11);

 int negR = 40;//IN3
 int posR = 42;//IN4
 int pwmR = 3;//ENB


 int negL = 46;//IN2
 int posL = 48;//IN1
 int pwmL = 2;//ENA

char val;
const int Rspeed = 200;
const int Lspeed = 200;
void setup() {
  pinMode(negR,OUTPUT);
  pinMode(posR,OUTPUT);
  pinMode(pwmR,OUTPUT);
  pinMode(negL,OUTPUT);
  pinMode(posL,OUTPUT);
  pinMode(pwmL,OUTPUT);
  Serial.begin(38400);
}


void loop()
{
  while(Serial.available())
  {
    val = Serial.read();
    if(val == 0)
      pause(0,0);
    else if(val == 1)
      forward(Rspeed,Lspeed);
    else if(val == 2)
      back(Rspeed,Lspeed);
    else if(val == 3)
      right(Rspeed,Lspeed);
    else if(val == 4)
      left(Rspeed,Lspeed);
    }
}

void forward(byte RmotorSpeed,byte LmotorSpeed)
{
  analogWrite(pwmR,RmotorSpeed);
  analogWrite(pwmL,LmotorSpeed);
  digitalWrite(posR,HIGH);
  digitalWrite(negR,LOW);
  digitalWrite(posL,LOW);
  digitalWrite(negL,HIGH);
}

void back(byte RmotorSpeed,byte LmotorSpeed)
{
  analogWrite(pwmR,RmotorSpeed);
  analogWrite(pwmL,LmotorSpeed);
  digitalWrite(posR,LOW);
  digitalWrite(negR,HIGH);
  digitalWrite(posL,HIGH);
  digitalWrite(negL,LOW);
}

void pause(byte RmotorSpeed,byte LmotorSpeed)
{
  analogWrite(pwmR,RmotorSpeed);
  analogWrite(pwmL,LmotorSpeed);
  digitalWrite(posR,LOW);
  digitalWrite(negR,LOW);
  digitalWrite(posL,LOW);
  digitalWrite(negL,LOW);
}

void right(byte RmotorSpeed,byte LmotorSpeed)
{
  analogWrite(pwmR,RmotorSpeed);
  analogWrite(pwmL,LmotorSpeed);
  digitalWrite(posR,LOW);
  digitalWrite(negR,LOW);
  digitalWrite(posL,LOW);
  digitalWrite(negL,HIGH);
}

void left(byte RmotorSpeed,byte LmotorSpeed)
{
  analogWrite(pwmR,RmotorSpeed);
  analogWrite(pwmL,LmotorSpeed);
  digitalWrite(posR,HIGH);
  digitalWrite(negR,LOW);
  digitalWrite(posL,LOW);
  digitalWrite(negL,LOW);
}

在串口输入数字就可以自主控制小车,注意要将波特率设成38400

Arduino使用HC05蓝牙模块控制小车

原文:https://www.cnblogs.com/zhongllmm/p/14401898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!