Raspberry Pi Robot Car: Motors, Chassis, Control
robot carmotorsl298nraspberry pirobotics
Wiring the L298N
- Motor driver's logic inputs (IN1-IN4) → any 4 free GPIO pins
- ENA/ENB (enable/speed control) → 2 PWM-capable GPIO pins
- Motor driver's 12V/VCC input → motor battery pack (not the Pi)
- Motor driver GND → shared common ground with the Pi's GND (critical — without a common ground reference, PWM signals won't read correctly)
- Motor outputs (OUT1-OUT4) → the two DC motors
Basic Control Code (gpiozero)
from gpiozero import Motor
left = Motor(forward=17, backward=27, enable=18)
right = Motor(forward=22, backward=23, enable=24)
def forward(speed=0.6):
left.forward(speed)
right.forward(speed)
def turn_left(speed=0.5):
left.backward(speed)
right.forward(speed)
forward()
gpiozero's Motor class handles the PWM enable pin and direction pins together — much less boilerplate than raw RPi.GPIO.
Adding Remote Control
Simplest path: a small Flask web server on the Pi serving a page with directional buttons that hit endpoints calling the motor functions — control it from any phone on the same WiFi network, no app needed. For lower latency, a gamepad over Bluetooth paired to the Pi with evdev reading joystick input works well too.
Adding Obstacle Avoidance
An HC-SR04 ultrasonic sensor (trigger/echo pins, 5V, cheap) mounted facing forward, polled in a loop — if distance drops below a threshold, stop and turn. This pairs naturally with the line-follower/obstacle-avoidance robot guide if you want to go further with sensor fusion.
Common Mistakes
- Forgetting the common ground between motor battery circuit and Pi circuit — causes erratic/no motor response even though wiring "looks right."
- Undersized motor battery — cheap 2xAA packs sag hard under stall current when the robot hits an obstacle, browning out the driver board.