Motor drivers and H-bridges
What you’ll learn
- How an H-bridge reverses a motor
- How PWM controls speed
- How to wire and code common driver boards
The H-bridge
Four switches around a motor, in the shape of an H. Close one diagonal pair and current flows one way; close the other pair and it flows the other way. A motor driver chip contains the H-bridge plus protection, controlled by your Arduino’s low-current pins and powered by the battery.
+V ──┬────────────┬── S1 S3 ├── (motor) ─┤ S2 S4 GND ─┴────────────┴── S1 + S4 on → forward S3 + S2 on → reversePWM: speed control
PWM (pulse-width modulation) switches power on and off very quickly. The fraction of time it’s on, the duty cycle, sets the average power. analogWrite(pin, value) with 0–255 does this on the UNO’s ~ pins (3, 5, 6, 9, 10, 11).
| analogWrite value | Duty cycle | Motor |
|---|---|---|
| 0 | 0% | Stopped |
| 128 | 50% | About half speed |
| 255 | 100% | Full speed |
Common drivers
| Driver | Notes |
|---|---|
| L298N | Very common, sturdy, but wastes about 2 V as heat. Pins: ENA (PWM speed), IN1/IN2 (direction) per motor |
| TB6612FNG | Small and efficient; PWMA/AIN1/AIN2 per motor plus STBY (must be HIGH) |
| L9110S | Tiny and cheap, two PWM inputs per motor |
Example: driving one motor with an L298N
const int ENA = 5, IN1 = 7, IN2 = 8;
void setup() { pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);}
void motorA(int speed) { // -255 to 255 digitalWrite(IN1, speed > 0); digitalWrite(IN2, speed < 0); analogWrite(ENA, abs(speed));}
void loop() { motorA(200); delay(2000); // forward motorA(0); delay(500); // stop motorA(-120); delay(2000); // slow reverse motorA(0); delay(500);}Example: the same idea for two motors
Write motorB() the same way with ENB, IN3, IN4, then build robot moves on top:
void drive(int left, int right) { motorA(left); motorB(right); }void spinLeft() { drive(-150, 150); }That’s exactly the motors(left, right) command in the robot simulator.
Direction tableEasy
For an L298N motor A, what do IN1 and IN2 need to be for forward, reverse and stop? Forward: IN1 HIGH, IN2 LOW. Reverse: IN1 LOW, IN2 HIGH. Stop: both LOW (or ENA = 0).
Duty cycleMedium
What analogWrite value gives a 30% duty cycle?
0.3 × 255 ≈ 77.
Soft startHard
Write a loop that ramps a motor from 0 to full speed over 1 second, to reduce the current spike.
Show an answer
for (int s = 0; s <= 255; s += 5) { motorA(s); delay(20); // 52 steps × 20 ms ≈ 1 s}Quick check
Finished this lesson?