How to Control Motor Direction with Arduino Easily
To control motor direction with
Arduino, use two digital pins connected to a motor driver or an H-bridge. Set one pin HIGH and the other LOW to make the motor spin forward, then reverse the pins to change direction.Syntax
Use two Arduino digital pins to control motor direction via an H-bridge or motor driver.
digitalWrite(pin1, HIGH): sets first control pin to HIGHdigitalWrite(pin2, LOW): sets second control pin to LOW- Reversing these signals changes motor direction
arduino
digitalWrite(pin1, HIGH); digitalWrite(pin2, LOW);
Example
This example shows how to control a DC motor direction using two pins connected to an H-bridge. The motor spins forward for 2 seconds, then reverses for 2 seconds repeatedly.
arduino
const int motorPin1 = 8; const int motorPin2 = 9; void setup() { pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); } void loop() { // Spin motor forward digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, LOW); delay(2000); // Stop motor briefly digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); delay(500); // Spin motor backward digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, HIGH); delay(2000); // Stop motor briefly digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); delay(500); }
Output
Motor spins forward for 2 seconds, stops briefly, then spins backward for 2 seconds, repeating.
Common Pitfalls
Common mistakes when controlling motor direction include:
- Not setting both pins as outputs with
pinMode(). - Setting both pins
HIGHor bothLOWunintentionally, which can stop the motor or cause short circuits. - Not using a proper motor driver or H-bridge, which can damage the Arduino or motor.
arduino
/* Wrong way: both pins HIGH - motor won't spin and may cause damage */ digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, HIGH); /* Right way: one HIGH, one LOW to control direction */ digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, LOW);
Quick Reference
| Action | Pin1 | Pin2 | Motor Behavior |
|---|---|---|---|
| Spin Forward | HIGH | LOW | Motor spins forward |
| Spin Backward | LOW | HIGH | Motor spins backward |
| Stop Motor | LOW | LOW | Motor stops |
| Avoid | HIGH | HIGH | Risk of short circuit or motor stop |
Key Takeaways
Use two digital pins with an H-bridge to control motor direction.
Set one pin HIGH and the other LOW to spin motor forward or backward.
Always set pins as outputs with pinMode before controlling them.
Never set both control pins HIGH simultaneously to avoid damage.
Use a proper motor driver to protect your Arduino and motor.