Using H-Bridge Motor Drivers

Understand how H-bridge motor drivers like the L298N control motor direction and speed for two-wheeled robots.

By Kevin McAleer,    3 Minutes

Page last updated May 10, 2025


Cover


An H-bridge is a circuit that lets you control the direction of a DC motor by switching the current flow. Itโ€™s essential for robotics because it allows you to drive motors forward and backward with just a few control signals.


โš™๏ธ How the H-Bridge Works

The H-bridge gets its name from the circuit diagram, which looks like an โ€œHโ€ made of transistors or switches.


It allows current to flow in either direction through the motor:

  • IN1 high, IN2 low โ†’ forward
  • IN1 low, IN2 high โ†’ backward
  • IN1 and IN2 same โ†’ brake/stop

When paired with PWM on the enable pin, you can also control the speed of the motor.


๐Ÿ”Œ Wiring Two Motors with L298N


The L298N has two H-bridges inside โ€” perfect for controlling two motors independently. Hereโ€™s a typical wiring setup:

  • Motor A
    • GP0 โ†’ IN1
    • GP1 โ†’ IN2
    • GP2 (PWM) โ†’ ENA
  • Motor B
    • GP3 โ†’ IN3
    • GP4 โ†’ IN4
    • GP5 (PWM) โ†’ ENB

GP pins are the GPIO pins on the Pico.


Donโ€™t forget: Pico GND must connect to L298N GND.


๐Ÿงช Writing the Code

Hereโ€™s a MicroPython script for controlling both motors:

from machine import Pin, PWM
from time import sleep

# Motor A
in1 = Pin(0, Pin.OUT)
in2 = Pin(1, Pin.OUT)
ena = PWM(Pin(2))
ena.freq(1000)

# Motor B
in3 = Pin(3, Pin.OUT)
in4 = Pin(4, Pin.OUT)
enb = PWM(Pin(5))
enb.freq(1000)

def motor_a_forward(speed=50000):
    in1.high()
    in2.low()
    ena.duty_u16(speed)

def motor_a_backward(speed=50000):
    in1.low()
    in2.high()
    ena.duty_u16(speed)

def motor_b_forward(speed=50000):
    in3.high()
    in4.low()
    enb.duty_u16(speed)

def motor_b_backward(speed=50000):
    in3.low()
    in4.high()
    enb.duty_u16(speed)

def stop_motors():
    in1.low()
    in2.low()
    in3.low()
    in4.low()
    ena.duty_u16(0)
    enb.duty_u16(0)

# Test
motor_a_forward()
motor_b_forward()
sleep(2)

motor_a_backward()
motor_b_backward()
sleep(2)

stop_motors()

๐Ÿค– Why This Matters

With two motors under your control, you can:

  • Drive forward/backward

  • Turn left/right

  • Rotate on the spot (tank steering)

This forms the basic movement logic for most two-wheeled robots.


๐Ÿงฉ Try It Yourself

Try setting different speeds for left and right motors.

  • Create a function to โ€œspin in place.โ€

  • Add buttons to manually control each motor.


Youโ€™re now ready to add some intelligence to your robot!

Next up: Line Following with IR Sensors


< Previous Next >

You can use the arrows  โ† โ†’ on your keyboard to navigate between lessons.