Due Motor Shield Example

This example shows how to drive a DC motor in forward and backward directions, using the Arduino Due and Motor Shield.

Hardware Required

  • Arduino Due
  • Arduino Motor Shield
  • DC motor
  • Wall wart power supply

Circuit

To build the circuit you need to mount the Arduino Motor Shield on top of the Arduino Due. Then you have to connect the two wires that comes out of the DC motor to the screw drivers terminals of the Motor Shield channel A. Last thing connect your wall wart power supply adapter to the DC connector of the Arduino Due. You must choose it respecting the voltage requirements of your DC motor. With the fan that we used in this example we provided 12V to the board.

Then plug your Arduino board into your computer, start the Arduino IDE 1.5, and enter the code below.

Connect the DC motor.
Connect the DC motor.

Arduino Due, Motor Shield and fan connected together.

Code

1const int
2PWM_A = 3,
3DIR_A = 12,
4BRAKE_A = 9,
5SNS_A = A0;
6
7
8void setup() {
9 // Configure the A output
10 pinMode(BRAKE_A, OUTPUT); // Brake pin on channel A
11 pinMode(DIR_A, OUTPUT); // Direction pin on channel A
12
13 // Open Serial communication
14 Serial.begin(9600);
15 Serial.println("Motor shield DC motor Test:\n");
16}
17
18void loop() {
19
20// Set the outputs to run the motor forward
21
22 digitalWrite(BRAKE_A, LOW); // setting brake LOW disable motor brake
23 digitalWrite(DIR_A, HIGH); // setting direction to HIGH the motor will spin forward
24
25 analogWrite(PWM_A, 255); // Set the speed of the motor, 255 is the maximum value
26
27 delay(5000); // hold the motor at full speed for 5 seconds
28 Serial.print("current consumption at full speed: ");
29 Serial.println(analogRead(SNS_A));
30
31// Brake the motor
32
33 Serial.println("Start braking\n");
34 // raising the brake pin the motor will stop faster than the stop by inertia
35 digitalWrite(BRAKE_A, HIGH); // raise the brake
36 delay(5000);
37
38// Set the outputs to run the motor backward
39
40 Serial.println("Backward");
41 digitalWrite(BRAKE_A, LOW); // setting againg the brake LOW to disable motor brake
42 digitalWrite(DIR_A, LOW); // now change the direction to backward setting LOW the DIR_A pin
43
44 analogWrite(PWM_A, 255); // Set the speed of the motor
45
46 delay(5000);
47 Serial.print("current consumption backward: ");
48 Serial.println(analogRead(SNS_A));
49
50 // now stop the motor by inertia, the motor will stop slower than with the brake function
51 analogWrite(PWM_A, 0); // turn off power to the motor
52
53 Serial.print("current brake: ");
54 Serial.println(analogRead(A0));
55 Serial.println("End of the motor shield test with DC motors. Thank you!");
56
57
58 while(1);
59}

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.