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

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

int motor1 = 13;
int motor2 = 12;
int Ena = 10;

int motor3 = 11;
int motor4 = 8;
int Enb = 9;

const int RxPin = 0;
const int TxPin = 1;

int dir;

void setup() {
 
 Serial.begin(9600);
 
 pinMode(motor1, OUTPUT);
 pinMode(motor2, OUTPUT);
 pinMode(Ena, OUTPUT);
 pinMode(motor3, OUTPUT);
 pinMode(motor4, OUTPUT);
 pinMode(Enb, OUTPUT);
 
 digitalWrite(motor1, LOW);
 digitalWrite(motor2, LOW);
 digitalWrite(motor3, LOW);
 digitalWrite(motor4, LOW);
 
 pinMode(RxPin, OUTPUT);
 pinMode(TxPin, INPUT);
}

void loop() {
 dir = Serial.read();
 
 switch(dir) {
 case 'f':
 case 'F':
 m_forward();
 break;
 case 'b':
 case 'B':
 m_back();
 break;
 case 'l':
 case 'L':
 m_left();
 break;
 case 'r':
 case 'R':
 m_right();
 break;
 default:
 m_stop();
 }
}

void m_forward() {
 digitalWrite(motor1, LOW);
 digitalWrite(motor2, HIGH);
 analogWrite(Ena, 250);
 digitalWrite(motor3, LOW);
 digitalWrite(motor4, HIGH);
 analogWrite(Enb, 250);
 Serial.println("forward");
 delay(100);
}

void m_back() {
 digitalWrite(motor1, HIGH);
 digitalWrite(motor2, LOW);
 analogWrite(Ena, 250);
 digitalWrite(motor3, HIGH);
 digitalWrite(motor4, LOW);
 analogWrite(Enb, 250);
 Serial.println("back");
 delay(100);
}

void m_left() {
 digitalWrite(motor1, HIGH);
 digitalWrite(motor2, LOW);
 analogWrite(Ena, 250);
 digitalWrite(motor3, LOW);
 digitalWrite(motor4, HIGH);
 analogWrite(Enb, 250);
 Serial.println("left");
 delay(100);
}

void m_right() {
 digitalWrite(motor1, LOW);
 digitalWrite(motor2, HIGH);
 analogWrite(Ena, 250);
 digitalWrite(motor3, HIGH);
 digitalWrite(motor4, LOW);
 analogWrite(Enb, 250);
 Serial.println("right");
 delay(100);
}

void m_stop() {
 digitalWrite(motor1, LOW);
 digitalWrite(motor2, LOW);
 digitalWrite(motor3, LOW);
 digitalWrite(motor4, LOW);
 Serial.println("stop");
 delay(100);
}