当前位置: 首页 > 工具软件 > Smart Car > 使用案例 >

Control Smart Car By Arduino

宋明亮
2023-12-01

通过Arduino Uno R3开发板控制小车向四个方向前进

需要的材料:

  • Arduino Uno R3
  • 小车底盘 + 轮胎(1个牛眼轮和2个普通轮胎) + 2个直流电机
  • L298N电机驱动模块
  • 7.4v锂电池组
  • Arduino IDE开发平台

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;   //电机停止速度
  • 在setup中定义I/O模式
 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);  
}

由于给定同样的电压,设定同样的速度,两边电机的速度不一定会相同,因此可根据实际的情况调节左右电机的速度,使其转速基本一致

 类似资料:

相关阅读

相关文章

相关问答