Control Stepper Motor Speed and Direction in Arduino Easily
To control a stepper motor's speed and direction in Arduino, use the
Stepper library or direct pin control. Adjust speed by setting the delay between steps and change direction by reversing the step sequence or using the step() function with positive or negative values.Syntax
The basic syntax to control a stepper motor with Arduino involves creating a Stepper object, setting its speed, and commanding it to move a number of steps.
Stepper stepsPerRevolution, pin1, pin2, pin3, pin4;- Defines the motor and pins.stepper.setSpeed(rpm);- Sets motor speed in revolutions per minute.stepper.step(steps);- Moves the motor a number of steps; positive for one direction, negative for the opposite.
arduino
Stepper stepper(200, 8, 9, 10, 11); void setup() { stepper.setSpeed(60); // 60 RPM } void loop() { stepper.step(100); // Move forward 100 steps delay(1000); stepper.step(-100); // Move backward 100 steps delay(1000); }
Example
This example shows how to control a 4-wire stepper motor's speed and direction using the Arduino Stepper library. It moves the motor forward and backward with a set speed.
arduino
#include <Stepper.h> const int stepsPerRevolution = 200; // change this to fit your motor // initialize the stepper library on pins 8 through 11: Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); void setup() { // set the speed at 30 rpm: myStepper.setSpeed(30); // initialize the serial port: Serial.begin(9600); } void loop() { Serial.println("Moving forward"); myStepper.step(stepsPerRevolution); // move one revolution forward delay(1000); Serial.println("Moving backward"); myStepper.step(-stepsPerRevolution); // move one revolution backward delay(1000); }
Output
Moving forward
Moving backward
Moving forward
Moving backward
...
Common Pitfalls
- Incorrect wiring: Make sure motor wires match the pin order in code.
- Wrong steps per revolution: Set the correct number of steps your motor needs for one full turn.
- Speed too high: Setting speed too fast can cause the motor to skip steps or stall.
- Not using delays: Without proper delays, the motor may not move smoothly.
arduino
/* Wrong: Using wrong steps per revolution */ Stepper myStepper(100, 8, 9, 10, 11); // Incorrect steps /* Right: Correct steps per revolution */ Stepper myStepper(200, 8, 9, 10, 11); // Correct steps
Quick Reference
Use this quick guide to control stepper motors with Arduino:
- Define motor:
Stepper stepsPerRevolution, pin1, pin2, pin3, pin4 - Set speed:
stepper.setSpeed(rpm) - Move steps:
stepper.step(steps)(positive or negative) - Delay: Add
delay()between moves for smooth operation
Key Takeaways
Use the Arduino Stepper library to simplify speed and direction control.
Set speed with setSpeed(rpm) and direction by positive or negative steps.
Match the motor's steps per revolution to your specific hardware.
Add delays between steps to prevent motor skipping or stalling.
Double-check wiring and pin assignments to avoid errors.