We use an H-Bridge to control the direction of a motor. It lets us make the motor spin forward or backward by changing the electric flow.
0
0
Motor direction with H-Bridge (L293D/L298N) in Arduino
Introduction
You want a robot car to move forward and backward.
You need to control a fan's rotation direction.
You want to reverse a conveyor belt's movement.
You are building a motorized door that opens and closes.
Syntax
Arduino
digitalWrite(pin1, HIGH); digitalWrite(pin2, LOW);
Set one pin HIGH and the other LOW to control motor direction.
Use two pins connected to the H-Bridge inputs for each motor.
Examples
This makes the motor spin forward.
Arduino
digitalWrite(2, HIGH); digitalWrite(3, LOW);
This makes the motor spin backward.
Arduino
digitalWrite(2, LOW); digitalWrite(3, HIGH);
This stops the motor by cutting power.
Arduino
digitalWrite(2, LOW); digitalWrite(3, LOW);
Sample Program
This program makes the motor spin forward for 2 seconds, stop for 1 second, spin backward for 2 seconds, then stop again. It repeats this cycle.
Arduino
#define motorPin1 2 #define motorPin2 3 void setup() { pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); } void loop() { // Spin motor forward digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, LOW); delay(2000); // run for 2 seconds // Stop motor digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); delay(1000); // stop for 1 second // Spin motor backward digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, HIGH); delay(2000); // run for 2 seconds // Stop motor digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); delay(1000); // stop for 1 second }
OutputSuccess
Important Notes
Always connect the H-Bridge power and ground correctly to avoid damage.
Use delays to see the motor direction changes clearly.
Make sure your motor power supply matches the motor's voltage rating.
Summary
Use two digital pins to control motor direction with an H-Bridge.
Set one pin HIGH and the other LOW to spin forward or backward.
Set both pins LOW to stop the motor.
