Arduino Code for Controlling a Stepper Motor
The Arduino programming environment comes with a function library for controlling a stepper motor.
To use the library, in the Arduino Editor from the top menu bar: Sketch > Import Library > Stepper.
Copy the example code below into an Arduino program.
Arduino code example
Example Code Notes
- The example code assumes that the stepper is being controlled by Arduino pins 4, 5, 6 and 7,
that connect to motor coil 1, 2, 3 and 4 (in that order) but you can use any set of four pins.
- The "#define STEPS 96" line defines the number of steps per rev. A 3.75 deg motor has 96 steps/rev while a 7.2 deg motor has 48 steps/rev.
- The "Stepper stepper(STEPS, 4, 5, 6, 7)" line is where you enter, in the right order, the four pins
used to control the stepper.
- The "stepper.setSpeed(x)" command sets the motor speed to x rpm.
- The "stepper.step(x)" command turns the motor x steps at the speed last set in the stepper.setSpeed() command. The motor turns one direction for postive x and the reverse direction for negative x.
- When the example program finishes, two of the coils will remain on, so all coils are turned off to
prevent your battery from draining.
- If you motor shudders but does not move, it is likely an error in the ordering of the coils.
Arduino Stepper Resources
Arduino tutorial for programming stepper motors:
Arduino stepper motor software library:
Example showing how to control a stepper with a potentiometer: