Arduino 蓝牙控制 L298N 直流电机驱动板附代码

一段蓝牙控制车子的代码,直流电机驱动板为 L298N,稍后补充更详细的资料。

    int Input1 = 13;    // motor A
    int Input2 = 12;
    int EnA = 10;

    int Input3 = 11;    // motor B
    int Input4 = 8;
    int EnB = 9;
    
    const int pinRx = 0;    //蓝牙数据传输接口(3.3V)
    const int pinTx = 1;
    
    int dir;        //运行控制
        
    void setup()
    {
      Serial.begin(9600);    //设置波特率
      
      pinMode(Input1, OUTPUT);   //左轮端口模式设置
      pinMode(Input2, OUTPUT);   //左轮端口模式设置
      pinMode(EnA, OUTPUT);
      pinMode(Input3, OUTPUT);   //右轮端口模式设置
      pinMode(Input4, OUTPUT);   //右轮端口模式设置
      pinMode(EnB,OUTPUT);
            
      digitalWrite(Input1, LOW);   //左轮端口模式初始化设置
      digitalWrite(Input2, LOW);   //左轮端口模式初始化设置
      digitalWrite(Input3, LOW);   //右轮端口模式初始化设置
      digitalWrite(Input4, LOW);   //右轮端口模式初始化设置
      
      pinMode(pinTx, OUTPUT);
      pinMode(pinRx, INPUT);
    }
    
    void loop()
    {
      dir = Serial.read();

      switch(dir)
      {
        case 'f':
           m_forward();
           break;
        case 'b':
           m_back();
           break;
        case 'l':
           m_left();
           break;
        case 'r':
           m_right();
           break;
        default:
           m_stop();
      }
    }
      void m_forward()    //前进
      {
        digitalWrite(Input1, LOW);
        digitalWrite(Input2, HIGH);
        analogWrite(EnA, 250);
        digitalWrite(Input3, LOW);
        digitalWrite(Input4, HIGH);
        analogWrite(EnB, 250);
        Serial.println("forward!");
        delay(1000);
      }
      
      void m_back()      //后退
      {
        digitalWrite(Input1, HIGH);
        digitalWrite(Input2, LOW);
        analogWrite(EnA, 250);
        digitalWrite(Input3, HIGH);
        digitalWrite(Input4, LOW);
        analogWrite(EnB, 250);
        Serial.println("back!");
        delay(1000);
      }
      
      void m_left()      //左拐弯
      {
        digitalWrite(Input1, HIGH);
        digitalWrite(Input2, LOW);
        analogWrite(EnA, 250);
        digitalWrite(Input3, LOW);
        digitalWrite(Input4, HIGH);
        analogWrite(EnB, 250);
        Serial.println("left!");
        delay(1000);
      }
      
      void m_right()     //右拐弯
      {
        digitalWrite(Input1, LOW);
        digitalWrite(Input2, HIGH);
        analogWrite(EnA, 250);
        digitalWrite(Input3, HIGH);
        digitalWrite(Input4, LOW);
        analogWrite(EnB, 250);
        Serial.println("right!");
        delay(1000);
      }
      
      void m_stop()      //停车
      {
        digitalWrite(Input1, LOW);
        digitalWrite(Input2, LOW);
        digitalWrite(Input3, LOW);
        digitalWrite(Input4, LOW);
        Serial.println("stop!");
        delay(1000);
      }