How to control a Stepper Motor with Arduino Motor Shield Rev3

Arduino Motor Shield Stepper Motor Tutorial

In this tutorial you will learn how to control a stepper motor with the Arduino Motor Shield Rev3. I have included a wiring diagram and many example codes.

First we take a look at an example that uses the Arduino Stepper library. This library is great when you are just starting out, but doesn’t have many extra features. 

I highly recommend to also take a look at the example codes for the AccelStepper library at the end of this tutorials. This library is fairly easy to use and can greatly improve the performance of your hardware.

After each example, I break down the code into smaller section and explain how it works. You should have no problems modifying the code to suit your needs, but if you have any questions, just leave a comment below.

What this article covers

If want to learn about other stepper motor drivers, take a look at the articles below.

Other stepper motor tutorials:

Information about the Arduino Motor Shield Rev3

The Arduino Motor Shield Rev3 is built around the L298 dual full-bridge driver, made by STMicroelectronics. With the shield you can drive DC motors, stepper motors, relays and solenoids. It comes with two separate channels, called A and B, that you can use to drive 2 DC motors, or 1 stepper motor when combined.

One thing that is very important to remember is that the L298 is a constant voltage driver. This means that the current draw depends on the relationship between the inductance and resistance (L/R) of the motor that you connect to it.

What this means for you, is that you you need to be careful when selecting the stepper motor and power supply to use with this shield. The shield’s operating voltage is between 5 and 12 volts. Since the shield can supply a maximum of 2 amperes per channel, you need to find a stepper motor that can be used in this voltage range and doesn’t exceed the maximum current rating. The motor I used for this tutorial draws around 1A at 5V. I also found this stepper motor from Adafruit that works great at 12V and only draws 350mA.

If the motor you want to drive doesn’t work with this shield, I recommend to look at a chopper drive instead. I wrote tutorials for the A4988 and DRV8825 driver that work great with many stepper motors.

Arduino Motor Shield Rev3 Specifications

Arduino Motor Shield Rev3Specifications
Operating voltage5V to 12V
Motor controllerL298P, Drives 2 DC motors or 1 stepper motor
Max current2A per channel or 4A max (with external power supply)
Current sensing1.65V/A
FunctionsFree running, stop and brake

For more information you can check out the datasheets here.

Input and Output

FunctionPins Channel APins Channel B
DirectionD12D13
PWMD3D11
BrakeD9D8
Current SensingA0A1

Things used in this project:

Hardware components

Parts are available on Amazon via the links below. You can click the plus sign on the right for additional information about the specific item.
NameDescriptionQuantityBuy
NEMA 17 stepper motorIn this tutorial I used a bipolar stepper motor with 4 wires. Try to find a stepper motor that can run at 5-12 V and doesn't exceed the 2 A current limit. This one from Adafruit works great at 12V and doesn't draw too much current (350 mA).x 1Amazon
Arduino Motor Shield Rev3This shield can also be used to drive 2 DC motors.x 1Amazon
Arduino UNO R3The motor shield works with the Arduino UNO. You can also use the SMD version.x 1Amazon
USB Type-B cableUsed to power the Arduino UNOx 1Amazon
Power supply (5-12V)The power supply should match the specifications of your stepper motor. Both should be around 5 - 12Vx 1Amazon

Tools

NameDescriptionBuy
Small screwdriverI like the Wiha PicoFinish.Amazon

Software

PictureNameLink
Arduino-LogoArduino IDE

*Note: the above links are affiliated which means – at no additional cost to you – if you purchase anything using them you’re helping to support my work on this site. My humble thanks (I really appreciate it)! 

Wiring - Connecting a stepper motor to the Arduino Motor Shield Rev3

The wiring diagram/schematic below shows you how to connect a stepper motor and power supply to the Arduino motor shield

Arduino-Motor-Shield-Rev3-with-Stepper-Motor-Wiring-Diagram-Schematic-Pinout-Fritzing
Wiring diagram for Arduino Motor Shield Rev3 with stepper motor.

The connections are also given in the table below.

Arduino Motor Shield Rev3 Connections

Arduino Motor Shield Rev3Connection
Vin5-12 V
GNDPower supply ground
A-Coil 1 of the stepper motor
A+Coil 1 of the stepper motor
B-Coil 2 of the stepper motor
B+Coil 2 of the stepper motor

Warning

It is possible to directly power the shield from the Arduino, but this is not recommended. When the stepper motor draws too much current, you can damage both the shield and the Arduino. I therefore recommend to use an external power supply for the motors. 

To do this you have to cut the Vin Connect jumper on the back of the shield. After doing this you can power the Arduino separately with a USB cable or via the 5.5 mm DC power jack.

Arduino-Motor-Shield-Rev3-Cutting-the-Vin-Connect-jumper
Cutting the Vin Connect jumper

How to determine the stepper motor wiring?

If you can’t find the datasheet of your stepper motor, it can be difficult to figure out how to wire your motor correctly. I use the following trick to determine how to connect 4 wire bipolar stepper motors:

The only thing you need to identify is the two pairs of wires which are connected to each of the two coils. One coil gets connected to A- and A+ and the other to B- and B+, the polarity doesn’t matter.

To find the two wires from one coil, do the following with the motor disconnected:

  1. Try to spin the shaft of the stepper motor by hand and notice how hard it is to turn.
  2. Now pick a random pair of wires from the motor and touch the bare ends together.
  3. Next, try to spin the shaft of the stepper motor again.

If you feel a lot of resistance, you have found a pair of wires from the same coil. If you can spin the shaft freely, try another pair of wires. Now connect the two coils to the pins shown in the wiring diagram above.

(If it is still unclear, please leave a comment below, more info can also be found on the RepRap.org wiki)

Basic Arduino example code for stepper motor and Arduino Motor Shield with Stepper.h library

You can upload the following example code to your Arduino using the Arduino IDE

This example uses the Stepper.h library, which should come pre-installed with the Arduino IDE. This sketch turns the stepper motor 1 revolution in one direction, pauses, and then turns 1 revolution in the other direction.

/*Example sketch to control a stepper motor with Arduino Motor Shield Rev3, Arduino UNO and Stepper.h library. More info: https://www.makerguides.com */

// Include the Stepper library:
#include <Stepper.h>

// Define number of steps per revolution:
const int stepsPerRevolution = 200; 

// Give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;

// Initialize the stepper library on the motor shield:
Stepper myStepper = Stepper(stepsPerRevolution,dirA,dirB);   

void setup() 
{    
  // Set the PWM and brake pins so that the direction pins can be used to control the motor:
  pinMode(pwmA, OUTPUT);
  pinMode(pwmB, OUTPUT);
  pinMode(brakeA, OUTPUT);
  pinMode(brakeB, OUTPUT);
  
  digitalWrite(pwmA, HIGH);
  digitalWrite(pwmB, HIGH);
  digitalWrite(brakeA, LOW);
  digitalWrite(brakeB, LOW);
  
  // Set the motor speed (RPMs):
  myStepper.setSpeed(60);
}


void loop() 
{
  // Step one revolution in one direction:
  myStepper.step(200);
  
  delay(2000);
  
  //Step on revolution in the other direction:
  myStepper.step(-200);
  
  delay(2000);
}

Code explanation:

The sketch starts by including the Stepper.h Arduino library. More information about this library can be found on the Arduino website

// Include the Arduino Stepper Library:
#include <Stepper.h>

Next I defined how many steps the motor takes to rotate 1 revolution. In this example we will be using the motor in full step mode. This means it takes 200 steps to rotate 360 degrees. You can change this value if you want if you are using a different type of stepper motor or setup.

// Define number of steps per revolution:
const int stepsPerRevolution = 200; 

After this, we define the motor connections (see specifications and wiring diagram above).

// Give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;
Next, you need to create a new instance of the Stepper class, which represents a particular stepper motor connected to the Arduino. For this we use the function Stepper(steps, pin1, pin2)  where steps is the number of steps per revolution and pin1 and pin2 are the pins used to drive the stepper motor. In our case this are dirA and dirB.
// Initialize the stepper library on the motor shield:
Stepper myStepper = Stepper(stepsPerRevolution,dirA,dirB); 

In this case I called the stepper motor ‘myStepper’ but you can use other names as well, like ‘z_motor’ or ‘liftmotor’ etc. Stepper liftmotor = Stepper(stepsPerRevolution, dirA, dirB);.

In the setup(), we start by setting the brake and pwm pins as output with the function pinMode(). The pwm pins need to be set HIGH and the brake pins LOW with the function digitalWrite().

  // Set the PWM and brake pins so that the direction pins can be used to control the motor:
  pinMode(pwmA, OUTPUT);
  pinMode(pwmB, OUTPUT);
  pinMode(brakeA, OUTPUT);
  pinMode(brakeB, OUTPUT);
  
  digitalWrite(pwmA, HIGH);
  digitalWrite(pwmB, HIGH);
  digitalWrite(brakeA, LOW);
  digitalWrite(brakeB, LOW);

You can set the speed of the motor in rpm with the function setSpeed(rpm). I set it to 60, so we should see 1 revolution per second.

  // Set the motor speed (RPMs):
  myStepper.setSpeed(60);

In the loop section of code, we simply call the step(steps) function which turns the motor a specific number of steps at a speed determined by the setSpeed(rpm) function. Passing a negative number to this function reverses the spinning direction of the motor.

void loop() 
{
  // Step one revolution in one direction:
  myStepper.step(200);
  
  delay(2000);
  
  //Step on revolution in the other direction:
  myStepper.step(-200);
  
  delay(2000);
}

Note that the step(steps) function is blocking, this means it will wait until the motor has finished moving to pass control to the next line in your sketch.

Example codes for Arduino Motor Shield and AccelStepper library

In the following three examples I will show you how you can control both the speed, the direction and the number of steps the stepper motor should take. In this example I will be using the AccelStepper library.

The AccelStepper library written by Mike McCauley is an awesome library to use for your project. One of the advantages is that it supports acceleration and deceleration, but it has a lot of other nice functions too. 

You can download the latest version of this library here or click the button below.

You can install the library by going to Sketch > Include Library > Add .ZIP Library… in the Arduino IDE.

Another option is to navigate to Tools > Manage Libraries… or type Ctrl + Shift + I on Windows. The Library Manager will open and update the list of installed libraries.

Installing an Arduino library step 1 open Library Manager

You can search for ‘accelstepper‘ and look for the library by Mike McCauley. Select the latest version and then click Install.

Installing an Arduino library step 2 AccelStepper

1. Continuous rotation example code

The following sketch can be used to run a stepper motor continuously at a constant speed. (No acceleration or deceleration is used).

You can open the code in a new window by clicking on the button in the top right corner of the code field.

/*Example sketch to control a stepper motor with Arduino Motor Shield Rev3, Arduino UNO and AccelStepper.h library. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>

// Define number of steps per revolution:
const int stepsPerRevolution = 200; 

// Give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;

// Define the AccelStepper interface type:
#define MotorInterfaceType 2

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(MotorInterfaceType, dirA, dirB);

void setup()
{
  // Set the PWM and brake pins so that the direction pins can be used to control the motor:
  pinMode(pwmA, OUTPUT);
  pinMode(pwmB, OUTPUT);
  pinMode(brakeA, OUTPUT);
  pinMode(brakeB, OUTPUT);
  
  digitalWrite(pwmA, HIGH);
  digitalWrite(pwmB, HIGH);
  digitalWrite(brakeA, LOW);
  digitalWrite(brakeB, LOW);
  
  // Set the maximum steps per second:
  stepper.setMaxSpeed(600); 
}

void loop()
{
  // Set the speed of the motor in steps per second:
  stepper.setSpeed(500);
  // Step the motor with constant speed as set by setSpeed():
  stepper.runSpeed();
}

How the code works:

Again the first step is to include the library with #include <AccelStepper.h>.
// Include the AccelStepper library:
#include <AccelStepper.h>

After specifying the connections like before, we need to define the motor interface type for the AccelStepper library. In this case we will be driving the stepper motor in full step mode, with two wires, so we set the mode to 2. You can find the other interface types here.

// Define the AccelStepper interface type:
#define MotorInterfaceType 2

Next, you need to create a new instance of the AccelStepper class with the appropriate motor interface type and connections.

In this case I called the stepper motor ‘stepper’ but you can use other names as well, like ‘z_motor’ or ‘liftmotor’ etc. AccelStepper liftmotor = AccelStepper(MotorInterfaceType, dirA, dirB);

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(MotorInterfaceType, dirA, dirB);

The setup() section of the code is mostly the same as the previous example, but I also defined the maximum speed in steps/second. Speeds of more than 1000 steps per second can be unreliable, so I set it to 600. Note that I specify the name of the stepper motor (‘stepper’), for which I want to define the maximum speed.

  // Set the maximum steps per second:
  stepper.setMaxSpeed(600); 

In the loop() we first set the speed that we want the motor to run at with the function setSpeed(). (you can also place this in the setup section of the code).

stepper.runSpeed() polls the motor and when a step is due, executes 1 step. This depends on the set speed and the time since the last step. If you want to change the direction of the motor, you can set a negative speed: stepper.setSpeed(-400); turns the motor the other way.

void loop()
{
  // Set the speed of the motor in steps per second:
  stepper.setSpeed(500);
  // Step the motor with constant speed as set by setSpeed():
  stepper.runSpeed();
}

2. Sketch to control number of steps or revolutions

With the following sketch you can control both the speed, direction and the number of steps/revolutions.

In this case, the stepper motor turns 1 revolution clockwise with 400 steps/sec, then turns 1 revolution counterclockwise at 200 steps/sec, and lastly turns 3 revolutions clockwise at 600 steps/sec.

/*Example sketch to control a stepper motor with Arduino Motor Shield Rev3, Arduino UNO and AccelStepper.h library. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>

// Define number of steps per revolution:
const int stepsPerRevolution = 200; 

// Give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;

// Define the AccelStepper interface type:
#define MotorInterfaceType 2

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(MotorInterfaceType, dirA, dirB);

void setup()
{
  // Set the PWM and brake pins so that the direction pins can be used to control the motor:
  pinMode(pwmA, OUTPUT);
  pinMode(pwmB, OUTPUT);
  pinMode(brakeA, OUTPUT);
  pinMode(brakeB, OUTPUT);
  
  digitalWrite(pwmA, HIGH);
  digitalWrite(pwmB, HIGH);
  digitalWrite(brakeA, LOW);
  digitalWrite(brakeB, LOW);
  
  // Set the maximum steps per second:
  stepper.setMaxSpeed(600); 
}

void loop()
{ 
  // Set the current position to 0:
  stepper.setCurrentPosition(0);
  
  // Run the motor forward at 400 steps/second until the motor reaches 200 steps (1 revolution):
  while(stepper.currentPosition() != 200)
  {
    stepper.setSpeed(400);
    stepper.runSpeed();
  }

  delay(1000);
  
  // Reset the position to 0:
  stepper.setCurrentPosition(0);
   
  // Run the motor backwards at 200 steps/second until the motor reaches -200 steps (1 revolution):
  while(stepper.currentPosition() != -200) 
  {
    stepper.setSpeed(-200);
    stepper.runSpeed();
  }
  
  delay(1000);
  
  // Reset the position to 0:
  stepper.setCurrentPosition(0);

  // Run the motor forward at 600 steps/second until the motor reaches 600 steps (3 revolutions): 
  while(stepper.currentPosition() != 600)
  {
    stepper.setSpeed(600);
    stepper.runSpeed();
  }
  
  delay(1000);
}

Code explanation:

The first part of the code up to the loop() section is exactly the same as in the previous example.

In the loop I make use of a while loop in combination with the currentPosition() function. First, I set the current position of the stepper motor to zero with stepper.setCurrentPosition(0)

  // Set the current position to 0:
  stepper.setCurrentPosition(0);

Next we make use of the while loop. A while loop will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. So in this case I check if the current position of the stepper motor is not equal to 200 steps (!= means: is not equal to). While this is not the case, we run the stepper motor at a constant speed as set by setSpeed().

  // Run the motor forward at 400 steps/second until the motor reaches 200 steps (1 revolution):
  while(stepper.currentPosition() != 200)
  {
    stepper.setSpeed(400);
    stepper.runSpeed();
  }

In the rest of the loop, we do exactly the same, just with a different speed and target position.

3. Acceleration and deceleration example code

In this example we will look at one of the main reasons to use the AccelStepper library.

With the following sketch you we can add acceleration and deceleration to the movements of the stepper motor, without any complicated coding. The first section of this sketch is the same as in example 1, but the setup and the loop are different.

The motor will run five revolutions back and forth with a speed of 200 steps per second and an acceleration of 50 steps/second2.

/*Example sketch to control a stepper motor with Arduino Motor Shield Rev3, Arduino UNO and AccelStepper.h library. More info: https://www.makerguides.com */

// Include the AccelStepper library:
#include <AccelStepper.h>

// Define number of steps per revolution:
const int stepsPerRevolution = 200; 

// Give the motor control pins names:
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;

// Define the AccelStepper interface type:
#define MotorInterfaceType 2

// Create a new instance of the AccelStepper class:
AccelStepper stepper = AccelStepper(MotorInterfaceType, dirA, dirB);

void setup()
{
  // Set the PWM and brake pins so that the direction pins can be used to control the motor:
  pinMode(pwmA, OUTPUT);
  pinMode(pwmB, OUTPUT);
  pinMode(brakeA, OUTPUT);
  pinMode(brakeB, OUTPUT);
  
  digitalWrite(pwmA, HIGH);
  digitalWrite(pwmB, HIGH);
  digitalWrite(brakeA, LOW);
  digitalWrite(brakeB, LOW);
  
  // Set the maximum steps per second:
  stepper.setMaxSpeed(200); 
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(50);
}

void loop()
{
  // Set target position:
  stepper.moveTo(1000);
  // Run to position with set speed and acceleration:
  stepper.runToPosition();
  
  delay(1000);

  // Move back to original position:
  stepper.moveTo(0);
  // Run to position with set speed and acceleration:
  stepper.runToPosition();
  
  delay(1000);
}

How the code works:

In the setup(), besides the maximum speed, we need to define the acceleration/deceleration. For this we use the function setAcceleration().

  // Set the maximum steps per second:
  stepper.setMaxSpeed(200); 
  // Set the maximum acceleration in steps per second^2:
  stepper.setAcceleration(50);

In the loop section of the code, I used a different way to let the motor rotate a predefined number of steps. First I set the target position with the function moveTo(). Next, we simply use the function runToPosition() to let the motor run to the target position with the set speed and acceleration. The motor will decelerate before reaching the target position.

  // Set target position:
  stepper.moveTo(1000);
  // Run to position with set speed and acceleration:
  stepper.runToPosition();

Finally, we set the new target position back to the 0, so that we return to the origin.

Conclusion

In this article I have shown you how you can control a stepper motor with the Arduino Motor Shield Rev3. We have looked at 4 examples, using both the Stepper and AccelStepper libraries. I hope you found it useful and informative. If you did, please share it with a friend that also likes electronics!

I would love to know what projects you plan on building (or have already built) with this Arduino Motor Shield. Please leave a comment down below and share your ideas.

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest
Share on email
Share on whatsapp

Beginner

Creative Commons License

If you have any questions, suggestions or if you think that things are missing in this tutorial, please leave a comment down below. Note that comments are held for moderation in order to prevent spam.

Leave a Reply

Your email address will not be published. Required fields are marked *