电机驱动模块在电子制作中会经常使用到,下面以L298N型号的模块为例介绍其使用方法。 模块引脚说明如下:
值得注意的是,它已经内置5V供电,所以不必从外面再接5V输入。 1、实验材料
2、接线
我们把零知标准板和电机驱动板相连接,驱动2路电机工作。接线图如下:
引脚连接: 最后我们把电机驱动板的12v接到一个9v的电源上(如干电池组),然后GND连接到零知标准板的地。 3、程序
根据上述连接线后,我们使用程序来控制电机的运行: /**
* 文件: 电机驱动.ino by 零知实验室
* -^^- 零知开源,让电子制作变得更简单! -^^-
* 时间: 2018/10/13 15:01
* 说明:
**/
//控制命令
#define STOP 0
#define FORWARD 1
#define BACKWARD 2
#define TURNLEFT 3
#define TURNRIGHT 4
//电机控制引脚
#define LEFT_MOTOR1 2
#define LEFT_MOTOR2 3
#define RIGHT_MOTOR1 4
#define RIGHT_MOTOR2 5
#define LEFT_ENA 11
#define RIGHT_ENB 12
int LED_STATE = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(LEFT_MOTOR1, OUTPUT);
pinMode(LEFT_MOTOR2, OUTPUT);
pinMode(RIGHT_MOTOR1, OUTPUT);
pinMode(RIGHT_MOTOR2, OUTPUT);
pinMode(LEFT_ENA,OUTPUT);
pinMode(RIGHT_ENB,OUTPUT);
motor_run(STOP);
}
void loop() {
// put your main code here, to run repeatedly:
int cmd = 1;
motor_run(cmd);
delay(1000);
motor_run(0);
}
把电机驱动的操作作为一个函数motor_run(int cmd);如下: /**
* 根据命令点击进行相应动作
* cmd 命令
*/
int highSpeed = 200;
int lowSpeed = 100;
void motor_run(int cmd)
{
switch(cmd)
{
case FORWARD:
Serial.println("FORWARD"); //输出状态
analogWrite(LEFT_ENA,highSpeed);
digitalWrite(LEFT_MOTOR1, LOW);
digitalWrite(LEFT_MOTOR2, HIGH);
analogWrite(RIGHT_ENB,highSpeed);
digitalWrite(RIGHT_MOTOR1, LOW);
digitalWrite(RIGHT_MOTOR2, HIGH);
break;
case BACKWARD:
Serial.println("BACKWARD"); //输出状态
digitalWrite(LEFT_MOTOR1, HIGH);
digitalWrite(LEFT_MOTOR2, LOW);
digitalWrite(RIGHT_MOTOR1, HIGH);
digitalWrite(RIGHT_MOTOR2, LOW);
break;
case TURNLEFT:
Serial.println("TURN LEFT"); //输出状态
analogWrite(LEFT_ENA,lowSpeed);
analogWrite(RIGHT_ENB,highSpeed);
digitalWrite(LEFT_MOTOR1, LOW);
digitalWrite(LEFT_MOTOR2, HIGH);//C
digitalWrite(RIGHT_MOTOR1, LOW);
digitalWrite(RIGHT_MOTOR2, HIGH);
break;
case TURNRIGHT:
Serial.println("TURN RIGHT"); //输出状态
analogWrite(LEFT_ENA,highSpeed);
analogWrite(RIGHT_ENB,lowSpeed);
digitalWrite(LEFT_MOTOR1, LOW);
digitalWrite(LEFT_MOTOR2, HIGH);
digitalWrite(RIGHT_MOTOR1, LOW);//C
digitalWrite(RIGHT_MOTOR2, HIGH);
break;
case STOP:
default:
Serial.println("STOP"); //输出状态
digitalWrite(LEFT_ENA,1);
digitalWrite(RIGHT_ENB,1);
digitalWrite(LEFT_MOTOR1, LOW);
digitalWrite(LEFT_MOTOR2, LOW);
digitalWrite(RIGHT_MOTOR1, LOW);
digitalWrite(RIGHT_MOTOR2, LOW);
break;
}
}
把程序上传到零知-标准板上,调整程序中cmd的值,看看效果吧!
|