How to Use Motor Shield with Arduino: Simple Guide
To use a
motor shield with Arduino, connect the shield to the Arduino board, then use the AFMotor library to control motors by specifying motor ports and speed. Write code to start, stop, and change motor direction using simple commands like motor.run() and motor.setSpeed().Syntax
The basic syntax to control a motor with the Arduino Motor Shield involves creating a motor object and using its methods:
AF_DCMotor motor(port_number);- creates a motor object on the specified port (1-4).motor.setSpeed(speed);- sets motor speed (0-255).motor.run(command);- runs the motor with commands likeFORWARD,BACKWARD,RELEASE.
This syntax requires including the AFMotor.h library.
arduino
#include <AFMotor.h> AF_DCMotor motor(1); // Motor connected to port 1 void setup() { motor.setSpeed(200); // Speed from 0 to 255 motor.run(FORWARD); // Run motor forward } void loop() { // Your motor control code here }
Example
This example shows how to run a motor forward at half speed for 2 seconds, then backward for 2 seconds, and then stop.
arduino
#include <AFMotor.h> AF_DCMotor motor(1); // Motor on port 1 void setup() { motor.setSpeed(128); // Half speed } void loop() { motor.run(FORWARD); // Run forward delay(2000); // Wait 2 seconds motor.run(BACKWARD); // Run backward delay(2000); // Wait 2 seconds motor.run(RELEASE); // Stop motor delay(2000); // Wait 2 seconds }
Common Pitfalls
Common mistakes when using a motor shield with Arduino include:
- Not installing or including the
AFMotorlibrary correctly. - Using wrong motor port numbers (valid ports are 1 to 4).
- Setting speed values outside the 0-255 range.
- Forgetting to power the motor shield separately if motors need more current.
- Not calling
motor.run(RELEASE)to stop the motor properly.
arduino
// Wrong: Using invalid port number #include <AFMotor.h> AF_DCMotor motor(5); // Invalid port, should be 1-4 // Right: #include <AFMotor.h> AF_DCMotor motor(2); // Valid port
Quick Reference
| Command | Description |
|---|---|
| AF_DCMotor motor(port) | Create motor object on port 1-4 |
| motor.setSpeed(value) | Set speed from 0 (stop) to 255 (full speed) |
| motor.run(FORWARD) | Run motor forward |
| motor.run(BACKWARD) | Run motor backward |
| motor.run(RELEASE) | Stop motor (release control) |
Key Takeaways
Connect the motor shield properly on the Arduino before coding.
Use the AFMotor library to control motors with simple commands.
Set motor speed between 0 and 255 for proper control.
Always stop motors with motor.run(RELEASE) to avoid damage.
Check motor port numbers and power supply to avoid common errors.