Instructables

Arduino Motor Shield Tutorial

Featured
Picture of Arduino Motor Shield Tutorial
The Arduino Motor Shield allows you to easily control motor direction and speed using an Arduino. By allowing you to simply address Arduino pins, it makes it very simple to incorporate a motor into your project. It also allows you to be able to power a motor with a separate power supply of up to 12v. Best of all, the shield is very easy to find. Aside from being sold a number of places online, they are now stocked by most Radioshack stores. For all of these reasons, the Arduino Motor Shield if a cool little to have in your arsenal for rapid prototyping, and general experimenting.
 
Remove these adsRemove these ads by Signing Up

Step 1: Install

Picture of Install
The pins of the official Arduino motor shield will only align with Arduino Uno Rev. 3.

In order to make it work with older versions of the Arduino, you will need to trim a few pins off the motor shield. However, this is not, at all, recommended.

Insert the motor shield pins into the socket of the Arduino Uno.

Step 2: Shield Features

Picture of Shield Features
The motor shield has 2 channels, which allows for the control of two DC motors, or 1 stepper motor.

It also has 6 headers for the attachment of Tinkerkit inputs, outputs, and communication lines. The use of these pins is somewhat limited, and therefor not covered in this tutorial.

With an external power supply, the motor shield can safely supply up to 12V and 2A per motor channel (or 4A to a single channel).

There are pins on the Arduino that are always in use by the shield. By addressing these pins you can select a motor channel to initiate, specify the motor direction (polarity), set motor speed (PWM), stop and start the motor, and monitor the current absorption of each channel .

The pin breakdown is as follows:

Function Channel A Channel B
Direction Digital 12 Digital 13
Speed (PWM) Digital 3 Digital 11
Brake Digital 9 Digital 8
Current Sensing Analog 0 Analog 1


For more information about the technical specs, check out the motor shield's official page on the Arduino site.

Step 3: Program

Picture of Program
2B.jpg
Plug the Arduino into your computer's USB port and open the Arduino development environment.

In order to get the board to do anything, you need to initialize the motor channel by toggling three parameters:
  1. First you need to set the motor direction (polarity of the power supply) by setting it either HIGH or LOW.
  2. Then you need to disengage the brake pin for the motor channel by setting it to LOW.
  3. Finally, to get the motor to start moving, you need to set the speed by sending a PWM command (analogWrite) to the appropriate pin.

If you do not do all three of these things, the motor will not turn on.

In the following steps are some common examples of common motor setups.

Step 4: One Motor

Picture of One Motor
3B.jpg
To control a motor using the Arduino Motor Shield, first plug the motor's positive (red) wire into Channel A's + terminal on the motor shield, and the motor's ground (black) wire into Channel A's - terminal on the shield.

An external power supply is not always necessary, but it drastically improves the motor's performance. It is recommended that you always use one.

To connect your external power supply, connect the positive (red) wire from the power supply to the "Vin" terminal, and the ground (black) wire to the "GND" terminal.

Finally, upload the code to control the Motor Shield to the Arduino.

Here is the code for controlling one motor:

Step 5: Two Motors

Picture of Two Motors
Interfacing with two motors is pretty much the same as interfacing with one motor. Simply plug the motor into Channel B.

The only difference code-wise is that you need to engage a second channel to control the second motor.

Here is code for controlling two motors:

Step 6: Stepper Motor

Picture of Stepper Motor
5B.jpg
5C.jpg
5D.jpg
5A.jpg
There are a number of different types of stepper motors, but in this tutorial we will specifically be addressing bipolar stepper motors. Bipolar stepper motors typically have 4 pins, which correspond to two coils. To use a stepper, you need to power these two coils in phase with alternating polarity.

To figure out which two pins make up a single coil, insert an LED into any two pins on its socket and rotate the motor shaft. If the LED lights up, you found one coil. The other two pins should make up the other coil.

To make a bipolar motor spin:
  1. Power the first coil.
  2. Next power the second coil with reverse polarity.
  3. Then power the first coil with reverse polarity.
  4. Finally, power the second coil.
To reverse the motor direction of a bipolar stepper, simply reverse the polarity of the second coil.

Here is code to make the stepper spin in one direction:

Here is code to make the stepper spin in the opposite direction:

1-40 of 90Next »
pavan2345673 months ago

My USB port connection is getting lost to the Arduino mega 2560 when i supply external current through an LED driver upto 1000mamp. I tried checking for 250ma and 350ma 0n the serial monitor by powering dc motors at 12v dc...it works fine but only at 1A and above the connection b/w usb port and controller is lost.

Kindly need suggestions to the earliest.?

chris9111 year ago
How do i write the code to make a momentary switch, start the motor. Without having to hold down the switch?

Hi there is sample code in the Arduin IDE for using a momentary switch. Here is my adaptation of it. Not sure if it actually works since I don't have an arduino handy.

/*
Button

The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int buttonPushed = 0; // button pushed variable. 0 means NOT PUSHED

void setup() {
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);

while (buttonPushed =0){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// get out of this loop by setting the value of x to 1
x = 1
}
}
}

void loop(){

// your motor code goes here

}

1eaper chris9116 months ago

I'm a newbie at the hardware, but from programming experience, I would say you need to make a boolean variable called running or something like that. Then when the button is pressed have an if statement that changes it to true if it is false and false if it is true. After that, only make the motor run when the variable is true.

Ok, apparently I am as lost as an easter egg. I need my stepper to move a certain number of degrees(steps) and stop. Then move a certain number back. I was under the impression that this is the advantage of a stepper... the fact that it STEPS. Why would I want to PWM a stepper when I could just use a regular DC motor?? I want it to do what it was designed to do, not dumb it down to be a regular motor.....

Tripou7 months ago
Hi there,

I'm a newbie on Arduino and I'd like to control a unipolar (6 wires) stepper motor with the rev3 shield. I've tried a few programs from myself and others but the m otor keeps making a sound without turning...
What I wantt to do first is making it turn on one way without stopping so that I can control its speed precisely.
Could anyone help me ?
shameet8 months ago
I have two stepper motors of these http://www.eminebea.com/en/product/rotary/steppingmotor/pm/highspeed/smw42s-48.shtml I have connected them on both the ends of a steel rod which is 5 mm diameter of length 50 cm Now i want turn the rod 45 degrees 1/4 turn when given a signal and back on signal Can some one help me with the code and the external power requirement for motor shield.
I am using this adafruit motor shield

http://www.adafruit.com/products/81

Adafruit Motor/Stepper/Servo Shield for Arduino kit - v1.2
triumphtotty8 months ago
This is exactly what I was looking for! I need to run a motor from a TIMER so that other code (serial commands) can be processed, so stripping your code down and reworking it into an ISR routine worked like a charm.

Thanks!

tt
cryptonomikon8 months ago
Hi, I'm a motor shield newbie. I've got the R3 Motor Shield and old Uno. I'm trying to figure out which pins are not needed.

If I align it the way you showed in on your picture, I could see that 4 pins do not match the Arduino headers. These pins are SCL, SDA, IOREF, and the pin before IOREF. Is this correct?

Where you discouraging the cutting of the extra pins because they could be useful someday? I am thinking of just bending them a bit and insulating them to prevent shorts. Or just cut off a small bit of the pins. What would you suggest?

Thanks!
ground up8 months ago
Thanks for the help now I know what I need to build a robot and how to program it.
Radioshack is closing out these units for $2.50 each.
And they're now sold out.
The store I was at was in the process of shipping two back, but I was there just in time to buy them.
critopadolf11 months ago
I am trying to control two motors, a servo, and a Ping sensor. am i able to connect the servo to one of the orange or white plugs to control it? or would i have to connect it normally to the arduino's pins
mikesevd1 year ago
Hello everyone!
I'm a new member and in arduino fun too (better late than never!). I've a couple of questions. Is the command myservo.attach(5 or 6) right when I connect a servo motor with the orange outputs of arduino motor shield? Since there are two ways to stick the three cables from a servo in that output, which one is the right one (should I use a voltmeter to find out?)? How can I use an extra power supply for a servo?
mike
johnmarc911 year ago
So, there are 6 plugs that I know is meant for Tinkerkit, I have regular motors, and would like to use them. I have found source code for controlling the tinkerkit, However that is only when using the Tinkerkit Motor shield. Anyone have any ideas for getting this to work?
holychachi1 year ago
I'm trying to come up with a way to control twelve steppers... Any ideas besides multiple driver boards?
shtranka1 year ago
i said what about connect two motor shields in one arduino card, and connect them ? can i have 12 * 2 v and 2* 2 A, is that doable !!
randofo (author)  shtranka1 year ago
I saw what you wrote. If they are 2.2 amps a piece, then you need a shield rated for at least 4.4 amps , and this shield can only handle 4 amps. That alone should indicate this shield is inappropriate. Typically you want a motor shield rated a fair amount above what your motor is rated for.

Also, you should figure out if you have two 12V motors or two 24V motors, because you have just said two different things.

From the link posted in the instructions above:

Summary
Operating Voltage 5V to 12V
Motor controller L298P, Drives 2 DC motors or 1 stepper motor
Max current 2A per channel or 4A max (with external power supply)
Current sensing 1.65V/A
shtranka1 year ago
if i have 2 DC motors 24v/2.2A each one can i use 2 motor shield with the same arduino card???
randofo (author)  shtranka1 year ago
You will need a larger motor controller for those. These shields can't really handle so much current.
THE STIG372 years ago
i am using the code given with dougstrickland's correction and i try to upload it and the motor isnt turning and i get an orange line of code at the bottom that says
avrdude: stk500_getsync(): not in sync: resp=0x00
I think that indicates an issue with the bootloader accepting your code. Can you run other code on it? Say, the blink code?

dman3 ringai1 year ago
what if the wheels aren't turning?
dman31 year ago
i uploaded this code but the wheels aren't turning...
any help?
thanks it was great for me , it works boss
AnAnalyst1 year ago
I could not follow your code so I wrote my own.  Here it is:

/*

This software will step (as opposed to wave or continuous drive) a two phase
4 wire stepper motor using the Arduino Mega 2560 and the Motor Shield Rev. 3

Of course, most of the examples I saw for stepper motor circuits didn't use
the Mega 2560.  This didn't prove to be an problem because the
Motor Shield Rev 3. is compatible with the Mega 2560. Just got to be careful
with the pin alignment when you stack the two boards.

While you can drive a stepper motor using the Motor Shield, trying to
understand it can be a bit difficult since the references on the schematic
have to do with driving a regular motor, not  a stepper motor.
So, to make the code more understandable, I redefined or relabeled the Pin Outs.

Note that Digital Out Pin 12 on the Shield corresponds to PWM 12 on
the Mega 2560 and so on.  If you are looking at the PIN Out for the CPU,
this corresponds to PB6.

As you probably already know, to energize a coil, you have to
connect one end to a positive voltage and the other end to ground. 
This way, current will flow from Positive to Ground. You can also
cause current to flow in the opposite direction by changing the voltages
in the other direction (Ground one end and apply a Positive voltage to the other).

If you are new to Adruino programming, make sure you use the exact case as
shown.  For example, Output is not the same as OUTPUT.
Also, don't forget the semicolon on the end of a program statement.

*/

/* There are many different ways(algorithms) that you use to drive
   your stepper motor.  Some provide more torque, some provide greater
   power savings.  The method you chose will depend on your
   over all design goals.
  
  
   The algorithm I coded up is know as the Full Step, Two Phase On.
   This implies that booth phases will be powered or energized at the
   same time. It has only four states per step so it's probably the
   easiest to code up.
     
    Sate        A1    B1   A2    B2
      1             H     H     L      L
      2             L      H    H      L
      3             L      L     H      H
      4             H     L     L       H

  
     
    
   If you execute states 1 - 4, it will turn clockwise.
   If you execute states 4 - 1, it will turn counter clockwise.
  
     
*/

// Redfine Pin Outs

//This is used to enable channel one on the driver chip.
//This corresponds to the PWMA on the driver schematic.
const int EnableOne = 3;

//This is used to enable channel two on the driver chip.
//This corresponds to PWMB on the driver schematic.
const int EnableTwo = 11;



//This corresponds to DIRA (referenced in two places) on the driver schematic.
const int CoilOneSideA = 12;

//Note that we are not going to define anything for the CoilOneSideB. The reason
//why is because it is controlled by the value at IN2 on the driver chip.
//The schematic shows it's connected to the output of a NAND gate.  The symbol is
//incorrect, it is an Exclusive Nor Gate.  The truth table for it is:
//   
//               X   Y   F
//               0   0   1      ******
//               0   1   0
//               1   0   0      ******
//               1   1   1
//
//The inputs to this gate are shown to be DIRA and BRAKE-A_DISABLE.
//If we set Break-A_Disable to a low or logic zero, the ouput(*) will be the opposite
//the other input, DIRA.  This is just what you need, a way to Invert DIRA.
//So now all you need to do is set the value for DIRA (CoilOneSideA) and the other
//side of the coil will always be at the opposite value.
//Note: If your design just used a driver chip, you  would need to drive or set the other
//side of the coil independently.
const int BreakADisable = 9;


//This corresponds to DIRB (Referenced in two places) on the schematic.
//Note that we are not going to define anything for the CoilTwoSideB for the same
//reason as discussed as above.
const int CoilTwoSideA = 13;

const int BreakBDisable = 8;

//This corresponds ro the SNSA on the schematic. If you use it, understand that it's analog.
//Right now it's not used.
const int CurrentSenseA = 0;

//This corresponds ro the SNSB on the schematic. If you use it, understand that it's analog.
//Right now it's not used.
const int CurrentSenseB= 1;

//I don't have a good feel for how long of a delay is needed but zero is
//not going to work to well.
int WaitTime  = 300;  //Setting this to longer values allows you watch each channel's LED



void setup() {
 
  //Set Pin Modes
  pinMode(EnableOne, OUTPUT);
  pinMode(EnableTwo, OUTPUT);
 
  pinMode (CoilOneSideA, OUTPUT);
  pinMode (BreakADisable, OUTPUT);
 
 
  pinMode (CoilTwoSideA, OUTPUT);
  pinMode (BreakBDisable, OUTPUT);
 
 
 
}

void loop()
{
  // This is the main code loop. It's where we energize the colis in on direction
  // and then in the other.
 
  int x = 100;
 
  for (x = 0; x <= 25; x++)
  {
     StepForward();
     // StepBackward();
  }
 
 

 
}

void StepForward()
{
  /*This is the step forward driver code*/
 
  //Enable both Changeless at the same time.
  digitalWrite(EnableOne,HIGH);
  digitalWrite (EnableTwo,HIGH);
 
 
  //Technically only have to do this once but I didn't want to code up
  //the logic to detect if this had been done before.
  digitalWrite(BreakADisable,LOW);
  digitalWrite(BreakBDisable,LOW);
 
  //Now energize the coils in following sequence
 
  digitalWrite(CoilOneSideA,HIGH);
  digitalWrite(CoilTwoSideA,HIGH);
 
  //Need to give the motor a finite amount of time to move before you try to make it move again.
  //this will also help reduce any moment over shoot or bounce.
  delay(WaitTime);
 
 
  digitalWrite(CoilOneSideA,LOW);
  //Leave CoildTwoSideA set to HIGH
 
  delay(WaitTime);
 
  //Leave CoilOneSideA set to Low
  digitalWrite(CoilTwoSideA,LOW);
 
  delay(WaitTime);
 
  digitalWrite(CoilOneSideA,HIGH);
  //Leave CoilTwoSideA set to low
 
  delay(WaitTime);
 
   
  //Now that you are done with the step, disable both Changeless.
  digitalWrite(EnableOne,HIGH);
  digitalWrite (EnableTwo,HIGH);
 
 
 
  
}

void StepBackward()
{
  /*This is the step backard driver code*/
 
  //Enable both Channles at the same time.
  digitalWrite(EnableOne,HIGH);
  digitalWrite (EnableTwo,HIGH);
 
 
  //Technically only have to do this once but I didn't want to code up
  //the logic to detect if this had been done before.
  digitalWrite(BreakADisable,LOW);
  digitalWrite(BreakBDisable,LOW);
 
  //Now energize the coils in foolowing sequence
 
  digitalWrite(CoilOneSideA,HIGH);
  digitalWrite(CoilTwoSideA,LOW);
 
  //Need to give the motor a fin tie amount of time to move before you try to make it move again.
  //this will also help reduce any moment over shoot or bounce.
  delay(WaitTime);
 
 
  digitalWrite(CoilOneSideA,LOW);
  //Leave CoildTwoSideA set to LOW
 
  delay(WaitTime);
 
  //Leave CoilOneSideA set to Low
  digitalWrite(CoilTwoSideA,HIGH);
 
  delay(WaitTime);
 
  digitalWrite(CoilOneSideA,HIGH);
  //Leave CoilTwoSideA set to HIGH
 
  delay(WaitTime);
 
   
  //Now that you are done with the step, disable both Channels.
  digitalWrite(EnableOne,HIGH);
  digitalWrite (EnableTwo,HIGH);
 
 
 
  
}
dudbarn1 year ago
I have copied and uploaded 2 of the programs to try. Both programs seem to upload fine, however, neither program has resulted in success of getting the motor to run. I am using a brand new arduino r3 and a brand new arduino motor shield. The wiring is hooked up as shown. Any help would be appreciated.
Thanks from a noob
mond2x dudbarn1 year ago
hi mr. dudbarn as i've read you message I think to a point that we have the same problem encountered. do you have any solution now. please reply any help would be appreciated.
thanks.
does this also work for a solenoid? I need it to spin in each direction.
fbasmajian1 year ago
you have an error with the serial port. you need to tools-serial port-and then change the serial port
Why can't I see my pictures on my post?
Hi, I have the same Arduino and same motor shield. I uploaded the sketch, but I can't make it do anything, and I mean anything. Do I have to change the serial port which is five now?

thanks.......
Hi there I'm new to the Arduino world and programming in general. I'm currently wanting to connect direction and on/off switches to my Arduino Uno/Motor Shield v3 and a bipolar stepper. I've read the previous posts regarding the code for this and think I understand it. The only part that I don't understand is where and how to connect the pushbutton switches to the Motor shield. I'm assuming there would be just one momentary switch for direction and one for on/off.
Thanks for any advise.
Justin
randofo (author)  justinmayer1 year ago
You should look at the Arduinio button and switch examples in the code library.

Any pin not being used by the Arduino shield can be set up as a switch input.

Check out intro to Arduino to get started.
Thanks for getting back to me randofo. I've looked at the switch examples and that was helpful. As far as I can tell the following code is designed to start and stop as well as change the direction of the stepper. If so, where do the switches fit in? Also where does the code tell the stepper how fast to turn?
What I'm trying to do is to be able to press a button that makes the stepper turn x amount of steps at x rpm in one direction and then automatically stop until I press the button again. The other button would do the same thing but in the opposite direction. Can you show me a code that would do this?
Thanks much, justinmayer
I
// 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;

void setup() {

//Setup Channel A
pinMode(dirA, OUTPUT); //Initiates Motor Channel A pin
pinMode(brakeA, OUTPUT); //Initiates Brake Channel A pin

//Setup Channel B
pinMode(dirB, OUTPUT); //Initiates Motor Channel A pin
pinMode(brakeB, OUTPUT); //Initiates Brake Channel A pin
randofo (author)  justinmayer1 year ago
That could just sets up the initial states of the Arduino. The loop code is what is making it spin, and it is only going clockwise.

You should check out the link thedanger just posted:
http://krisarnold.com/2012/02/03/arduino-and-the-official-motor-shield-r3/
Thanks. Yes I have seen krisarnold's code which fills in more pieces of the puzzle. I still don't see any code for on/off, direction SWITCHES however! Am I missing something?
randofo (author)  justinmayer1 year ago
Those you are going to have to write! You should look into if-statements....

There are many ways to do this, but one way which might work for you is....

psudo-code:

if switch 1 triggered to "on"{
if switch 2 triggered left{
move motor left
}
else{
move motor right
}
}

Thanks randofo. I decided to see if I could simply have a pushbutton switch just start the stepper turning when I press it and stop it when I let go.
So far the code uploaded without any errors but the stepper does not spin when I press the button but the brakes are on either way!
Any ideas? Thanks, Justin

// Include the Stepper Library
#include

// Map our pins to constants to make things easier to keep track of
const int pwmA = 3;
const int pwmB = 11;
const int brakeA = 9;
const int brakeB = 8;
const int dirA = 12;
const int dirB = 13;
const int switchPin = 7;

// The amount of steps for a full revolution of your motor.
// 360 / stepAngle
const int STEPS = 200;

// Initialize the Stepper class
Stepper myStepper(STEPS, dirA, dirB);

void setup() {
// Set the RPM of the motor
myStepper.setSpeed(50);

//
pinMode(switchPin, INPUT);

// Turn on pulse width modulation
pinMode(pwmA, OUTPUT);
digitalWrite(pwmA, HIGH);
pinMode(pwmB, OUTPUT);
digitalWrite(pwmB, HIGH);

// Turn off the brakes
pinMode(brakeA, OUTPUT);
digitalWrite(brakeA, LOW);
pinMode(brakeB, OUTPUT);
digitalWrite(brakeB, LOW);


}

void loop()
{
if (digitalRead(switchPin == HIGH)
){
// Turn on pulse width modulation
pinMode(pwmA, OUTPUT);
digitalWrite(pwmA, HIGH);
pinMode(pwmB, OUTPUT);
digitalWrite(pwmB, HIGH);

// Turn off the brakes
pinMode(brakeA, OUTPUT);
digitalWrite(brakeA, LOW);
pinMode(brakeB, OUTPUT);
digitalWrite(brakeB, LOW);
}
else
{
// Turn off pulse width modulation
pinMode(pwmA, OUTPUT);
digitalWrite(pwmA, LOW);
pinMode(pwmB, OUTPUT);
digitalWrite(pwmB, LOW);

// Turn on the brakes
pinMode(brakeA, OUTPUT);
digitalWrite(brakeA, HIGH);
pinMode(brakeB, OUTPUT);
digitalWrite(brakeB, HIGH);
}



}
1-40 of 90Next »