Control DC motors with an Arduino

Arduino Uno tutorials

🕑 This lesson will take about 20 minutes

In this lesson, you will learn how to use connect DC motors to an Arduino and control the speed and direction of the motors. You can extend this project by using a 2WD chassis and car kit to build an autonomous vehicle (follow this tutorial).

Required parts

Here is what you will need:

  • 1 x Arduino Uno board

  • 1 x 4 AA battery holder

  • 4 x AA batteries

  • 1 x L298P Shield R3 DC Motor shield

  • 6 x wires to connect motors and the battery holder to the motor shield (2 wires should be soldered to each motor)

  • Flat head/slotted screw driver

  • Arduino IDE software (free at http://www.arduino.cc)

The three images below show the 2WD car kit before assembly, the Arduino Uno board, the L298P motor shield, and the assembled car.

Connecting the DC motors and battery pack to the Arduino

If you don’t already have wires soldered to the DC motors, then you will need to solder two wires to each motor (a black wire for ground and a red wire for voltage).

  1. Stack the Motor Shield on top of the Arduino Uno carefully, ensuring the pins match up in their correct position and don’t get bent or damaged.

  2. Insert the red wire from the battery enclosure into the VIN slot on the Motor Shield. Use a small screwdriver to clamp the wire into the slot.

  3. Insert the black wire from the battery enclosure into the GND slot on the Motor Shield. Use a small screwdriver to clamp the wire into the slot.

  4. Insert the red wire from one motor (we’ll call it Motor A) to the A+ slot on the Motor Shield, and the black wire from Motor A to the A- slot on the Motor Shield. Use a small screwdriver to clamp the wires into their slots.

  5. Connect the red wire from the other motor (Motor B) to the B+ slot on the Motor Shield, and the black wire from Motor B to the B- slot on the Motor Shield. Use a small screwdriver to clamp the wires into their slots.

  6. Connect the Arduino Uno board to the computer via the USB cable and upload the code below using the Arduino IDE software.

  7. Insert four AA batteries in the battery enclosure (if you don’t have a battery pack, the motors should be able to turn using power through the USB cable).

If your motors turn in the wrong direction or don’t move, check that you have the Motor pins in the correct places and make sure no pins are loose.

The code

Use the following code to test that the motors turn. Modify the code to change the speed or direction of the motors.