AI Robotics Tutorial for Beginners in 2026: Build a Raspberry Pi Robot That Avoids Obstacles

I remember the first time I tried to build a robot that actually “thinks”—it was a mess. Spaghetti wiring, a neural network that refused to converge, and a robot that spun in circles. But by 2026, the tools have matured so much that a beginner can pull off a real AI-powered robot in a weekend. Here’s exactly how I did it, step by step. This is a hands-on AI robotics tutorial beginner 2026 style, with real code, real commands, and zero fluff.

What You’ll Build

You’ll build a small wheeled robot that uses a camera and a lightweight neural network to avoid obstacles. It runs on a Raspberry Pi 4, uses TensorFlow Lite for inference, and moves with a standard motor driver. By the end, you’ll have a robot that drives around your desk without crashing into walls.

Hardware Requirements

Here’s what I used. You can substitute similar parts, but stick to the Raspberry Pi 4 for the best beginner experience. Prices are approximate as of early 2026.

Component Recommended Model Approx. Cost (USD)
Microcontroller Raspberry Pi 4 (4GB RAM) $55
Camera Raspberry Pi Camera Module 3 $25
Motor Driver L298N Dual H-Bridge $10
Motors & Wheels 2x DC gear motors with wheels $15
Battery 5V power bank (for Pi) + 6V battery pack (for motors) $20
Chassis Acrylic or 3D printed base $10

Total under $140. That’s cheaper than a good dinner out, and you get a robot that actually learns.

Software Setup

Before you wire anything, get the Pi ready. I used Raspberry Pi OS Lite (64-bit) because it’s lean. Flash it to an SD card using the Raspberry Pi Imager. Then SSH in:

ssh pi@raspberrypi.local
# default password: raspberry

Update everything:

sudo apt update && sudo apt upgrade -y

Install the essentials:

sudo apt install python3-pip python3-opencv git -y

Install TensorFlow Lite runtime (not the full TensorFlow — it’s too heavy for a Pi 4):

pip3 install tflite-runtime

Enable the camera interface:

sudo raspi-config
# Navigate to Interface Options > Camera > Enable

Reboot:

sudo reboot

Step 1: Wiring the Motor Driver

I’ll keep this simple. The L298N has two channels: one for the left motor, one for the right. Connect the Pi’s GPIO pins to the driver’s input pins. Here’s my mapping:

  • GPIO 17 → IN1 (left motor forward)
  • GPIO 18 → IN2 (left motor backward)
  • GPIO 22 → IN3 (right motor forward)
  • GPIO 23 → IN4 (right motor backward)
  • GPIO 24 → ENA (PWM enable left)
  • GPIO 25 → ENB (PWM enable right)

Connect the motor power supply (I used a 6V battery pack) to the L298N’s 12V input (yes, it works with 6V). The Pi’s 5V pin powers the logic side of the driver. Don’t skip the ground connection between Pi and driver.

Step 2: Test the Motors

Create a file motors_test.py:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# Motor pins
IN1, IN2, IN3, IN4 = 17, 18, 22, 23
ENA, ENB = 24, 25

for pin in [IN1, IN2, IN3, IN4, ENA, ENB]:
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, GPIO.LOW)

# PWM for speed control
pwm_a = GPIO.PWM(ENA, 100)
pwm_b = GPIO.PWM(ENB, 100)
pwm_a.start(50)
pwm_b.start(50)

# Forward 2 seconds
GPIO.output(IN1, GPIO.HIGH)
GPIO.output(IN2, GPIO.LOW)
GPIO.output(IN3, GPIO.HIGH)
GPIO.output(IN4, GPIO.LOW)
time.sleep(2)

# Stop
GPIO.output(IN1, GPIO.LOW)
GPIO.output(IN2, GPIO.LOW)
GPIO.output(IN3, GPIO.LOW)
GPIO.output(IN4, GPIO.LOW)
pwm_a.stop()
pwm_b.stop()
GPIO.cleanup()

Run it:

python3 motors_test.py

If the robot moves forward, you’re good.

Step 3: Capture a Frame and Run a Simple AI Model

I trained a tiny neural network on a dataset of “obstacle” vs “clear” images. You can download my pre-trained model (it’s a 50KB TensorFlow Lite model) from my GitHub. For this tutorial, I’ll give you the code that uses it. The model takes a 64×64 grayscale image and outputs a probability of obstacle.

First, install the camera module:

sudo apt install python3-picamera2 -y

Create ai_vision.py:

import cv2
import numpy as np
from picamera2 import Picamera2
import tflite_runtime.interpreter as tflite
import time

# Load the model
interpreter = tflite.Interpreter(model_path="obstacle_avoid.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Initialize camera
picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"size": (640, 480)}))
picam2.start()

# Helper: preprocess image
def preprocess(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    resized = cv2.resize(gray, (64, 64))
    input_data = np.expand_dims(resized.astype(np.float32) / 255.0, axis=0)
    input_data = np.expand_dims(input_data, axis=-1)  # add channel dim
    return input_data

# Single inference
def predict_obstacle(frame):
    input_data = preprocess(frame)
    interpreter.set_tensor(input_details[0]['index'], input_data)
    interpreter.invoke()
    output = interpreter.get_tensor(output_details[0]['index'])
    return output[0][0]  # higher = obstacle

# Test
for _ in range(5):
    frame = picam2.capture_array()
    prob = predict_obstacle(frame)
    print(f"Obstacle probability: {prob:.2f}")
    time.sleep(1)

picam2.stop()
cv2.destroyAllWindows()

Run it:

python3 ai_vision.py

If you see values close to 0.0 for clear space and >0.8 for a hand in front, the model works.

Step 4: Combine AI and Motors

Now we glue everything together. The robot will capture a frame, run the model, and decide: go forward if clear, turn left if obstacle is in front. I’ll also add a simple state machine to avoid getting stuck.

Create robot_controller.py:

import RPi.GPIO as GPIO
import time
import cv2
import numpy as np
from picamera2 import Picamera2
import tflite_runtime.interpreter as tflite

# GPIO setup (same as before)
IN1, IN2, IN3, IN4 = 17, 18, 22, 23
ENA, ENB = 24, 25
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
for pin in [IN1, IN2, IN3, IN4, ENA, ENB]:
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, GPIO.LOW)
pwm_a = GPIO.PWM(ENA, 100)
pwm_b = GPIO.PWM(ENB, 100)
pwm_a.start(40)
pwm_b.start(40)

# Motor control functions
def forward():
    GPIO.output(IN1, GPIO.HIGH); GPIO.output(IN2, GPIO.LOW)
    GPIO.output(IN3, GPIO.HIGH); GPIO.output(IN4, GPIO.LOW)

def stop():
    GPIO.output(IN1, GPIO.LOW); GPIO.output(IN2, GPIO.LOW)
    GPIO.output(IN3, GPIO.LOW); GPIO.output(IN4, GPIO.LOW)

def turn_left():
    GPIO.output(IN1, GPIO.LOW); GPIO.output(IN2, GPIO.HIGH)
    GPIO.output(IN3, GPIO.HIGH); GPIO.output(IN4, GPIO.LOW)

# Load AI model
interpreter = tflite.Interpreter(model_path="obstacle_avoid.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Camera
picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"size": (640, 480)}))
picam2.start()

def preprocess(frame):
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    resized = cv2.resize(gray, (64, 64))
    input_data = np.expand_dims(resized.astype(np.float32) / 255.0, axis=0)
    input_data = np.expand_dims(input_data, axis=-1)
    return input_data

def predict(frame):
    data = preprocess(frame)
    interpreter.set_tensor(input_details[0]['index'], data)
    interpreter.invoke()
    return interpreter.get_tensor(output_details[0]['index'])[0][0]

# Main loop
try:
    while True:
        frame = picam2.capture_array()
        prob = predict(frame)
        print(f"Obstacle prob: {prob:.2f}")
        if prob > 0.7:
            print("Obstacle! Turning left...")
            stop()
            time.sleep(0.2)
            turn_left()
            time.sleep(0.5)  # turn 90 degrees roughly
            stop()
        else:
            print("Clear. Moving forward.")
            forward()
        time.sleep(0.1)
except KeyboardInterrupt:
    stop()
    pwm_a.stop()
    pwm_b.stop()
    GPIO.cleanup()
    picam2.stop()

Run it:

python3 robot_controller.py

Watch your robot navigate. It’s simple but it works. If you put a box in front, it’ll turn away.

What You Should Do Next

This is a minimal AI robotics tutorial for 2026. The model I used is just a binary classifier. You can improve it by:

  • Collecting your own dataset (take 100+ images of your room with and without obstacles) and retraining the model on a PC.
  • Adding a distance sensor (like an HC-SR04) for redundancy.
  • Using a Raspberry Pi 5 if you want faster inference (the Pi 4 handles it at ~5 FPS, which is fine for crawling speed).

In my experience, the biggest mistake beginners make is skipping the wiring test. Always test motors and camera separately before integrating AI. I’ve fried two Pi GPIO pins by rushing. Avoid that.

Now go build your own AI robot. The 2026 tools are easier than ever, and the feeling of watching something you coded drive around on its own is genuinely addictive—it’s the moment a beginner realizes they’ve crossed into real robotics.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top