zoukankan      html  css  js  c++  java
  • 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 Pin42 - 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

  • 相关阅读:
    依赖注入与控制反转
    Java NIO(三)
    Java NIO(二)
    Java NIO(一)
    Jetty 的基本架构
    spring IOC
    java代理
    spring AOP
    linux 添加用户并授权可以操作文件夹
    Centos6.5 yum 安装jdk1.8
  • 原文地址:https://www.cnblogs.com/zhongllmm/p/14401898.html
Copyright © 2011-2022 走看看