本篇介紹步進電機驅(qū)動庫的使用,通過讀取電位器輸入,控制步進電機轉(zhuǎn)動相應角度。
Stepper庫是官方提供的驅(qū)動庫,我們啟動Arduino IDE,點擊「文件」—「示例」就能找到Stepper庫,官方提供了四個例程。關(guān)于Stepper庫可參考官方介紹。
1. 實驗材料
- Uno R3開發(fā)板
- 配套USB數(shù)據(jù)線
- 面包板及配套連接線
- ULN2003驅(qū)動板
- 步進電機
- 電位器
2. 實驗步驟
1. 根據(jù)原理圖搭建電路。
原理圖在上一篇基礎上添加了電位器的連接。ULN2003驅(qū)動板上IN1、IN2、IN3、IN4分別連接UNO開發(fā)板的數(shù)字引腳2,3,4,5;驅(qū)動板電源輸入+、-引腳分別連接UNO開發(fā)板的5V、GND;電位器中間引腳連接Uno模擬引腳A0,電位器兩端引腳分別連接Uno的5V和GND。
實驗原理圖如下圖所示:

實驗原理圖
實物連接圖如下圖所示:

實物連接圖
2. 修改Stepper源文件。
由于我們使用的步進電機和官方驅(qū)動庫中有所差異,所以需要對驅(qū)動庫稍加修改。
- 找到Arduino IDE安裝目錄,進入\libraries\Stepper\src\,用文本文件打開Stepper.cpp。將255行switch包含的case注釋掉。

庫文件
- 拷貝如下代碼到switch中。
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, HIGH);
break;
case 3: //1001
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;

修改后
- 保存并關(guān)閉Stepper.cpp。
3. 新建sketch,拷貝如下代碼替換自動生成的代碼并進行保存。
/*
* MotorKnob
*
* A stepper motor follows the turns of a potentiometer
* (or other sensor) on analog input 0.
*
* http://www.arduino.cc/en/Reference/Stepper
* This example code is in the public domain.
*/
#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2, 3, 4, 5);
// the previous reading from the analog input
int previous = 0;
void setup() {
// set the speed of the motor to 90 RPMs
stepper.setSpeed(90);
}
void loop() {
// get the sensor value
int val = analogRead(0);
// move a number of steps equal to the change in the
// sensor reading
stepper.step(val - previous);
// remember the previous value of the sensor
previous = val;
}
4. 連接開發(fā)板,設置好對應端口號和開發(fā)板類型,進行程序下載。

程序下載
3. 實驗現(xiàn)象
步進電機跟隨電位器旋轉(zhuǎn)而轉(zhuǎn)動。

實驗現(xiàn)象
4. 實驗分析
程序中使用Stepper庫,設置步進電機四相驅(qū)動引腳,設置轉(zhuǎn)動速度。主循環(huán)中讀取A0口模擬輸入,與上次數(shù)據(jù)作比較,以上次數(shù)據(jù)為參考點驅(qū)動步進電機轉(zhuǎn)動。