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

  1. 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.
  2. 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.
  3. 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.
  4. The "stepper.setSpeed(x)" command sets the motor speed to x rpm.
  5. 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.
  6. When the example program finishes, two of the coils will remain on, so all coils are turned off to prevent your battery from draining.
  7. 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:
http://www.arduino.cc/en/Tutorial/StepperUnipolar

Arduino stepper motor software library:
http://arduino.cc/en/Reference/Stepper

Example showing how to control a stepper with a potentiometer:
http://arduino.cc/en/Tutorial/MotorKnob