让我们来看看如何编写代码来控制一个步进电机。
介绍一个很好的单片机模拟网站:https://wokwi.com/
首先来看看如何使用Arduino直接驱动步进电机,注意这种方法只能用来驱动很小的步进电机,因为Arduino板子输出的电流大小有限。
现在Wokwi中新建一个Arduino项目,添加一个步进电机,然后建立如下连线:
A- –> 11
A+ –>10
B+ –>9
B- –>8

代码如下:
/*---------------------------------------*\
| Simple direct drive of Bipolar Stepper |
\*---------------------------------------*/
// pins connected
#define Ap 10 // A+ line
#define Am 11 // A- line
#define Bp 9 // .
#define Bm 8 // .
void setup() {
// set output
pinMode(Ap,OUTPUT); pinMode(Am,OUTPUT);
pinMode(Bp,OUTPUT); pinMode(Bm,OUTPUT);
}
int I = 0 ;
void loop() {
// This is Wave Fullstep motion - only one coil energized at a time
if ( I++ <100) { // stop after 25*4 steps (=100) - quarter turn with gearRatio "2:1"
delay(10);
digitalWrite(Bm,LOW);
digitalWrite(Bp,LOW);
digitalWrite(Am,LOW);
digitalWrite(Ap,HIGH);
delay(10);
digitalWrite(Bm,LOW);
digitalWrite(Bp,HIGH);
digitalWrite(Am,LOW);
digitalWrite(Ap,LOW);
delay(10);
digitalWrite(Bm,LOW);
digitalWrite(Bp,LOW);
digitalWrite(Am,HIGH);
digitalWrite(Ap,LOW);
delay(10);
digitalWrite(Bm,HIGH);
digitalWrite(Bp,LOW);
digitalWrite(Am,LOW);
digitalWrite(Ap,LOW);
} else while(1);
}
以上代码将依次激活马达中的四对线圈,运行代码后,应可以看到步进电机顺时针转动一圈。
再看如何使用驱动芯片来驱动步进电机,添加一个A4988驱动,进行以下连线。

步进电机到驱动芯片:
A- –>1B
A+ –>1A
B+–>2A
B- –> 2B
驱动芯片到Arduino:
STEP–>Pin3
DIR–>Pin4
VDD–>5v
GND–>GND
注意要将芯片上的Sleep和Rest Pin短接
代码:
// Define pin connections
const int stepPin = 3; // Pin connected to STEP
const int dirPin = 4; // Pin connected to DIR
// Define steps per revolution for your motor
const int stepsPerRevolution = 200; // Adjust for your motor
void setup() {
// Set pins as outputs
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
// Set initial direction
digitalWrite(dirPin, HIGH); // HIGH for one direction, LOW for the other
}
void loop() {
// Rotate the motor one way
digitalWrite(dirPin, HIGH); // Set direction
stepMotor(stepsPerRevolution); // Move a full revolution
delay(1000); // Wait for a second
// Rotate the motor the other way
digitalWrite(dirPin, LOW); // Reverse direction
stepMotor(stepsPerRevolution); // Move a full revolution
delay(1000); // Wait for a second
}
// Function to make the motor step
void stepMotor(int steps) {
for (int i = 0; i < steps; i++) {
digitalWrite(stepPin, HIGH); // Step pin HIGH
delayMicroseconds(1000); // Adjust for speed control (lower value for faster)
digitalWrite(stepPin, LOW); // Step pin LOW
delayMicroseconds(1000); // Adjust for speed control
}
}
运行程序后应可以看到步进电机轮流正反转动一圈。