Obstacle-Avoiding Robot with Raspberry Pi
A 4WD rover that measures distance with ultrasound and turns away from walls on its own.
This is the classic first robot: two motor channels, one distance sensor and a simple decision loop. It teaches motors, sensors, power and code all at once.
Video tutorial

Video by Robojax, embedded from YouTube. The written steps below are our own and match the parts list.
Mission steps
Build the chassis
Assemble the kit, pair the left motors and right motors together and route the wires to the top plate.
Wire the motor driver
TB6612FNG: AIN1/AIN2/PWMA to GPIO5/6/12, BIN1/BIN2/PWMB to GPIO13/19/26, STBY to GPIO25. Motor power (VM) from the battery; logic (VCC) from 3V3.
Wire the sensor safely
HC-SR04 runs on 5 V and its ECHO pin outputs 5 V. Use a voltage divider (1 kΩ + 2 kΩ) on ECHO before it reaches GPIO24. TRIG goes to GPIO23.
Power
Run the Pi from a 5 V 3 A UBEC fed by the 18650 pack. Join all grounds.
Run the code
The loop drives forward until something is closer than 25 cm, then backs up and turns.
Code
from gpiozero import Robot, Motor, DistanceSensor, OutputDevice
from time import sleep
OutputDevice(25).on() # TB6612 standby off
bot = Robot(left=Motor(5, 6, enable=12), right=Motor(13, 19, enable=26))
eye = DistanceSensor(echo=24, trigger=23, max_distance=2)
while True:
if eye.distance < 0.25:
bot.backward(0.5); sleep(0.4)
bot.right(0.6); sleep(0.5)
else:
bot.forward(0.6)
sleep(0.05)Tip: test every script on the bench before installing it in a moving machine.
Questions
My robot drives in circles
One side is wired backwards. Swap that motor pair's two wires at the driver.