电子说
课程目标
电路搭建
所需材料
ArduinoUNO * 1
L298N驱动模块 * 1
直流电机 * 2
7~12V外接电源 * 1
杜邦线若干
小车组件
电路连接
程序编写
练习一:小车的循环运动
通过编写程序,循环实现小车的前进一秒、后退一秒、左转一秒、右转一秒、停止一秒功能。
图形化方式:
如果有同学发现,按照下面的程序上传后,小车的运动有问题,那么可以通过改变直流电机的接线或者修改数字输出引脚的高低电平即可。
代码方式:
/* 项目名称:循环控制小车运动
* 项目时间:2022.03.28
* 项目作者:MRX
*/
int IN1 = 4; // IN1连接 D4
int IN2 = 5;
int ENA = 9;
int IN3 = 6; // IN3连接D6
int IN4 = 7;
int ENB = 10;
unsigned long delaytime = 1000; //等待时间
int value = 100; // 模拟输出的值
//前进
void forward() {
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
analogWrite(ENA,value);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
analogWrite(ENB,value);
}
//后退
void back() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,value);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,value);
}
//右转
void right() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,value);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,0);
}
//左转
void left() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,0);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,value);
}
// 停止
void stop() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,LOW);
analogWrite(ENA,0);
digitalWrite(IN3,LOW);
digitalWrite(IN4,LOW);
analogWrite(ENB,0);
}
void setup(){
for (int i = 4;i <= 10;i++){
pinMode(i, OUTPUT);
}
}
void loop(){
forward();
delay(delaytime);
forward();
delay(delaytime);
left();
delay(delaytime);
right();
delay(delaytime);
stop();
delay(delaytime);
}
练习二:可调速的小车
通过读取可调电位器的值,来实现车速的变化。
电路接线:
在上图的基础上,增加一个可调电位器连接到UNO的A0脚。
图形化方式:
代码方式:
/* 项目名称:电位器控制小车速度
* 项目时间:2022.03.28
* 项目作者:MRX
*/
int IN1 = 4; // IN1 connected to pin 4
int IN2 = 5;
int ENA = 9;
int IN3 = 6; // IN3 connected to pin 6
int IN4 = 7;
int ENB = 10;
unsigned long delaytime = 1000; //delay time
int value = 0; // the duty cycle
void forward() {
digitalWrite(IN1,HIGH);
digitalWrite(IN2,LOW);
analogWrite(ENA,value);
digitalWrite(IN3,HIGH);
digitalWrite(IN4,LOW);
analogWrite(ENB,value);
}
void back() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,value);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,value);
}
void right() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,100);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,0);
}
void left() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
analogWrite(ENA,0);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
analogWrite(ENB,100);
}
void stop() {
digitalWrite(IN1,LOW);
digitalWrite(IN2,LOW);
analogWrite(ENA,0);
digitalWrite(IN3,LOW);
digitalWrite(IN4,LOW);
analogWrite(ENB,0);
}
void setup(){
for (int i = 4;i <= 10;i++){
pinMode(i, OUTPUT);
}
pinMode(A0,INPUT);
}
void loop(){
value = (map(analogRead(A0), 0, 1023, 0, 255));
forward();
}
全部0条评论
快来发表一下你的评论吧 !