其他分享
首页 > 其他分享> > Arduino使用HC05蓝牙模块控制小车

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

作者:互联网

 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

标签:analogWrite,Arduino,digitalWrite,蓝牙,RmotorSpeed,HC05,LOW,byte,LmotorSpeed
来源: https://www.cnblogs.com/zhongllmm/p/14401898.html