通过Arduino Uno R3开发板控制小车向四个方向前进
需要的材料:
1、首先,我们需要搭好小车的模型,两个直流电机用于驱动轮胎,牛眼轮方便转向和便于调节小车直线行走
2、将直流电机接在L298N电机驱动模块上,驱动模块可控制直流电机顺时针和逆时针的旋转,同时驱动模块连接在Arudino控制板上,最后接上电池组供电
3、在Arduino IDE中,编写相关的程序用于控制电机,实现转动
#define motorLeftF 9 //左电机正转 PWM
#define motorLeftB 5 //左电机反转 PWM
#define motorRightB 6 //右电机反转 PWM
#define motorRightF 10 //右电机正转 PWM
int motorSpeedRun = 150; //电机前进速度
int motorSpeedStop = 0; //电机停止速度
pinMode(motorRightB, OUTPUT);
pinMode(motorRightF, OUTPUT);
pinMode(motorLeftB, OUTPUT);
pinMode(motorLeftF, OUTPUT);
void turnForward(){
digitalWrite(motorLeftF, HIGH);
digitalWrite(motorLeftB, LOW);
analogWrite(motorLeftF, motorSpeedRun + 5);
digitalWrite(motorRightF, HIGH);
digitalWrite(motorRightB, LOW);
analogWrite(motorRightF, motorSpeedRun - 2);
}
void turnBack(){
digitalWrite(motorLeftF, LOW);
digitalWrite(motorLeftB, HIGH);
analogWrite(motorLeftB, motorSpeedRun - 2);
digitalWrite(motorRightF, LOW);
digitalWrite(motorRightB, HIGH);
analogWrite(motorRightB, motorSpeedRun + 2);
}
void turnLeft(){
digitalWrite(motorRightF, HIGH);
digitalWrite(motorRightB, LOW);
analogWrite(motorRightF, motorSpeedRun);
digitalWrite(motorLeftF, LOW);
digitalWrite(motorLeftB, LOW);
}
void turnLeftOriginal(){
digitalWrite(motorRightF, HIGH);
digitalWrite(motorRightB, LOW);
analogWrite(motorRightF, motorSpeedRun);
digitalWrite(motorLeftF, LOW);
digitalWrite(motorLeftB, HIGH);
analogWrite(motorLeftB, motorSpeedRun);
}
void turnRight(){
digitalWrite(motorLeftF, HIGH);
digitalWrite(motorLeftB, LOW);
analogWrite(motorLeftF, motorSpeedRun);
digitalWrite(motorRightF, LOW);
digitalWrite(motorRightB, LOW);
}
void turnRightOriginal(){
digitalWrite(motorRightF, LOW);
digitalWrite(motorRightB, HIGH);
analogWrite(motorRightB, motorSpeedRun);
digitalWrite(motorLeftF, HIGH);
digitalWrite(motorLeftB, LOW);
analogWrite(motorLeftF, motorSpeedRun);
}
void turnStop(){
digitalWrite(motorLeftF, LOW);
digitalWrite(motorLeftB, LOW);
digitalWrite(motorRightF, LOW);
digitalWrite(motorRightB, LOW);
}
由于给定同样的电压,设定同样的速度,两边电机的速度不一定会相同,因此可根据实际的情况调节左右电机的速度,使其转速基本一致