最新消息:

Arduino基础入门篇27—步进电机驱动库的使用

Arduino 少儿编程 2137浏览 0评论

本篇介绍步进电机驱动库的使用,通过读取电位器输入,控制步进电机转动相应角度。

Stepper库是官方提供的驱动库,我们启动Arduino IDE,点击「文件」—「示例」就能找到Stepper库,官方提供了四个例程。关于Stepper库可参考官方介绍(https://www.Arduino.cc/en/Reference/Stepper)。

1. 实验材料

  • Uno R3开发板

  • 配套USB数据线

  • 面包板及配套连接线

  • ULN2003驱动板

  • 步进电机

  • 电位器

2. 实验步骤

1. 根据原理图搭建电路。

原理图在上一篇基础上添加了电位器的连接。ULN2003驱动板上IN1、IN2、IN3、IN4分别连接UNO开发板的数字引脚2,3,4,5;驱动板电源输入+、-引脚分别连接UNO开发板的5V、GND;电位器中间引脚连接Uno模拟引脚A0,电位器两端引脚分别连接Uno的5V和GND。

实验原理图如下图所示:

Arduino基础入门篇27—步进电机驱动库的使用
实验原理图

实物连接图如下图所示:

Arduino基础入门篇27—步进电机驱动库的使用
实物连接图

2. 修改Stepper源文件。

由于我们使用的步进电机和官方驱动库中有所差异,所以需要对驱动库稍加修改。

  • 找到Arduino IDE安装目录,进入librariesSteppersrc,用文本文件打开Stepper.cpp。将255行switch包含的case注释掉。

Arduino基础入门篇27—步进电机驱动库的使用
库文件
  • 拷贝如下代码到switch中。

 1case 0:  // 1010
 2  digitalWrite(motor_pin_1, HIGH);
 3  digitalWrite(motor_pin_2, LOW);
 4  digitalWrite(motor_pin_3, LOW);
 5  digitalWrite(motor_pin_4, LOW);
 6break;
 7case 1:  // 0110
 8  digitalWrite(motor_pin_1, LOW);
 9  digitalWrite(motor_pin_2, HIGH);
10  digitalWrite(motor_pin_3, LOW);
11  digitalWrite(motor_pin_4, LOW);
12break;
13case 2:  //0101
14  digitalWrite(motor_pin_1, LOW);
15  digitalWrite(motor_pin_2, LOW);
16  digitalWrite(motor_pin_3, HIGH);
17  digitalWrite(motor_pin_4, HIGH);
18break;
19case 3:  //1001
20  digitalWrite(motor_pin_1, LOW);
21  digitalWrite(motor_pin_2, LOW);
22  digitalWrite(motor_pin_3, LOW);
23  digitalWrite(motor_pin_4, HIGH);
24break;

如下如所示:

Arduino基础入门篇27—步进电机驱动库的使用
修改后
  • 保存并关闭Stepper.cpp。

3. 新建sketch,拷贝如下代码替换自动生成的代码并进行保存。

 1/*
 2 * MotorKnob
 3 *
 4 * A stepper motor follows the turns of a potentiometer
 5 * (or other sensor) on analog input 0.
 6 *
 7 * http://www.arduino.cc/en/Reference/Stepper
 8 * This example code is in the public domain.
 9 */
10
11#include <Stepper.h>
12
13// change this to the number of steps on your motor
14#define STEPS 200
15
16// create an instance of the stepper class, specifying
17// the number of steps of the motor and the pins it's
18// attached to
19Stepper stepper(STEPS, 2345);
20
21// the previous reading from the analog input
22int previous = 0;
23
24void setup() {
25  // set the speed of the motor to 90 RPMs
26  stepper.setSpeed(90);
27}
28
29void loop() {
30  // get the sensor value
31  int val = analogRead(0);
32
33  // move a number of steps equal to the change in the
34  // sensor reading
35  stepper.step(val - previous);
36
37  // remember the previous value of the sensor
38  previous = val;
39}

4. 连接开发板,设置好对应端口号和开发板类型,进行程序下载。

Arduino基础入门篇27—步进电机驱动库的使用
程序下载

3. 实验现象

步进电机跟随电位器旋转而转动。

Arduino基础入门篇27—步进电机驱动库的使用
实验现象

4. 实验分析

程序中使用Stepper库,设置步进电机四相驱动引脚,设置转动速度。主循环中读取A0口模拟输入,与上次数据作比较,以上次数据为参考点驱动步进电机转动。

转自公众号:
TonyCode

您必须 登录 才能发表评论!