Here example code for controlling stepper motor using Arduino are provided. By have all example codes in one place we can compare the codes for different stepper motor applications. For example some uses different stepper motor driver hardware, there are different arduino library for stepper motor etc.
There are many ways to control a stepper motor, eg, wired or wireless and different types of stepper motor step sequences(full step, half step etc) that can be used. Hence there will be different step motor Arduino code depending upon what hardware and the stepper sequence is used which in turn depends upon the application of the stepper motor.
For example stepper motor like Nema17 used in 3D printers can be controlled using L298N H-bridge IC, or motor shield such as L293D based Arduino Motor Shield or using stepper motor driver IC like Pololu A4988 (capable of driving up to 1.5A stepper motors) or DRV8825 (capable of driving up to 2A stepper motors) which are better alternative to L298N. The difference between these are like the current and voltage they can deliver to the motor, number of pins required to run the motor, additional components required like flywheel diodes etc.
But perhaps the simplest way to test a stepper motor control is perhaps using H-bridge driver IC like L298N with a microcontrollor or microcontroller board like Arduino. When using dedicated IC like L298N additional diodes are required. For circuit implementation see Step Motor Arduino Code control with L298N.
The Arduino step code for control is repeated here:
int en = 10;
int in1 = 9;
int in2 = 8;
int in3 = 7;
int in4 = 6;
const int sw=2;
int swstate;
const int t= 10;
void cw()
{
analogWrite(en, 200);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(t);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(t);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(t);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(t);
}
void ccw()
{
analogWrite(en, 200);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(t);
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(t);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
delay(t);
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
delay(t);
}
void setup(){
//set motor control pins to outputs
pinMode(en, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
//switch
pinMode(sw,INPUT_PULLUP);
}
void loop() {
peripheral_loop();
swstate = digitalRead(sw);
if(swstate == HIGH){
cw();
}
else{
ccw();
}
}
Another similar stepper motor control circuit is the stepper motor control with potentiometer. Here the step motor code for arduino is such that when the potentiometer knob is rotated, it moves the stepper motor. Here a library called AccelStepper is used. The stepper motor program for this is below.
//Program for acceleration control for Stepper Motor using potentiometer, L298N & Arduino
//Source: https://ee-diary.blogspot.com
#include <AccelStepper.h>
//define pins for stepper motor
int en = 10;
int in1 = 9;
int in2 = 8;
int in3 = 7;
int in4 = 6;
//define pin for potentiometer
int potPin = A0;
int fullstep = 4; //number of stages in full drive
int halfstep = 8; //number of stages in half drive
int stepdrive = fullstep; //select step drive mode
//define stepper motor with step mode and inputs
AccelStepper stepper(stepdrive, in1, in2, in3, in4);
int steps = (stepdrive/4)*200; //number of steps per revolution
unsigned long revTime = 0;
//Set minimum and maximum speed in rpm
float rpmMin = 10.0;
float rpmMax = 50.0;
//Calculate minimum and maximum speed in steps/s
float speedMin = rpmMin*steps/60.0;
float speedMax = rpmMax*steps/60.0;
//variables
float rpm;
int anaValue, s;
void setup(){
Serial.begin(9600); //set Serial output baud rate
pinMode(en, OUTPUT); //set enable
digitalWrite(en, HIGH);
stepper.setMaxSpeed((stepdrive/4)*800); //max speed 800 or 1600 steps/s
stepper.setAcceleration(500); //set acceleration rate (steps/s^2)
//For output format
Serial.println("Outputs:");
Serial.println("Revol. Time(secs) RPM Speed(steps/sec)");
Serial.println("-------------------------------------------------------------\n");
}
void loop() {
anaValue = analogRead(potPin); // potentiometer voltage
// map voltage to speed (step/s)
s = map(anaValue, 0, 1023, speedMin, speedMax);
stepper.move(100); //move the internal motor 100 steps
stepper.setSpeed(s); //set the internal motor speed
stepper.runSpeed(); //run the stepper motor
//For each complete revolution
if((stepper.currentPosition() % steps)==0) {
revTime = millis()-revTime; // time (ms) for one revolution
rpm = stepper.speed()*60.0/steps; // stepper motor rpm
//Outputs
//Print Revolution Time
Serial.print(String(revTime)+"s \t\t\t");
//Print RPM
Serial.print(String(rpm,2)+"rpm\t\t");
//Print Speed
Serial.println(String(stepper.speed(),0)+"steps/sec");
delay(25); //delay 25ms to prevent any duplicates
revTime=millis(); //update revolution start time
}
}
The arduino stepper motor code is also different on how you want to control and what you want to control about the stepper motor. For example you can control a stepper motor speed, direction, acceleration. For circuit implementation and program code see stepper motor speed and direction control. The program code is repeated here:
//Program for speed and direction control for Stepper Motor with L298N & Arduino
#include <Stepper.h>
//define pins for stepper motor
int en = 10;
int in1 = 9;
int in2 = 8;
int in3 = 7;
int in4 = 6;
int Tsteps = 200; //total steps for Nema 17 is 200
//define stepper motor total steps and inputs
Stepper stepper(Tsteps, in1, in2, in3, in4);
int dir = 1; //rotation direction
int Trevs; //revolution time
float t, r; //time for revolution and number of revolution
void setup(){
pinMode(en, OUTPUT);
digitalWrite(en, HIGH);
Serial.begin(9600); //Serial output baud rate
Serial.println("Stepper Motor RPM(speed), No.of Revolution & Time required for Revolution");
}
void loop(){
// increase motor speed from 2 to 32 rpm
for (int s = 2; s<100; s=s+4){
stepper.setSpeed(s); //set motor speed
dir = -dir; // change direction of rotation
Trevs = millis(); // set start time (ms)
stepper.step(dir * Tsteps/2); //move number of 1/2 of total steps(200)
Trevs = millis()-Trevs; //time for half revolution(ms)
delay(500); //time delay of 0.5secs
t = Trevs/1000.0; //time required to move steps
r = s*t/60.0; //number of revolutions
//Outputs
Serial.println("-----------Outputs------------\n");
//print RPM
Serial.println("RPM:"+String(s));
//print number of revolutions
Serial.println("No.of Revol.:"+String(r,2));
//print time required for revolution
Serial.println("Time Reqd.:"+String(t)+" secs");
Serial.print("\n");
}
}
In the above Arduino program code, we have used the Stepper library.
A stepper motor can also be controlled with Arduino using different step modes, including single coil steps, double coil steps, interleaved coil steps, and microsteps. An example program code is below.
As said earlier, the arduino code for the step motor control also depends upon the medium connection between the stepper motor and the Arduino. For example we can also control the step motor wirelessly. An example was provided in wireless stepper motor control with Arduino.
The transmitter and receive codes is repeated here and is provided below.
Transmitter Code:
#include <RH_ASK.h>
#include <SPI.h>
RH_ASK rf_driver;
void setup()
{
Serial.begin(9600);
if (!rf_driver.init())
Serial.println("init failed");
}
void loop()
{
static int counter = 0;
uint8_t data[1];
data[0] = counter;
counter++;
rf_driver.send(data, sizeof(data));
rf_driver.waitPacketSent();
Serial.println("Sending data: " + String(counter));
delay(1000);
}
Receiver Code:
#include <RH_ASK.h>
#include <Stepper.h>
#include <SPI.h>
#define stepsPerRevolution 200
RH_ASK rf_driver;
Stepper myStepper(stepsPerRevolution, 7, 8, 9, 10);
void setup()
{
Serial.begin(9600);
if (!rf_driver.init())
Serial.println("init failed");
myStepper.setSpeed(60);
}
void loop()
{
uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
uint8_t buflen = sizeof(buf);
if (rf_driver.recv(buf, &buflen))
{
Serial.print("Message received: ");
for (int i = 0; i < buflen; i++)
{
Serial.print(buf[i]);
}
Serial.println();
myStepper.step(buf[0]);
}
}
Here, a wireless RF circuit well known as 433MHz RF module that is compatible with Arduino is used. From the program code perspective, a wireless control Arduino library called RH_ASK is used. There are two step motor control codes, one for transmitter and one for the receiver.