How to Control DC, Stepper, and Servo Motors with Raspberry Pi and OpenClaw Agents
Raspberry Pi shipped 7.6 million boards in fiscal year 2025, yet most motor tutorials still cover only one motor type and stop at manual remote control. This guide compares DC, stepper, and servo motors side by side, walks through wiring and Python code for each, and shows how OpenClaw agents can translate natural language into motor sequences on the Pi.
Why Motor Controllers Matter for Pi-Based Agents
Raspberry Pi shipped 7.6 million boards and modules in fiscal year 2025, a 9% increase over the prior year, according to the company's annual results published in March 2026. The installed base now exceeds 68 million units worldwide. A growing share of those boards end up in robotics projects, from two-wheel obstacle avoiders to multi-axis robotic arms.
Yet the default Pi motor tutorial has barely changed in a decade. Wire an L298N driver, write a Python loop, map keyboard presses to motor directions. Forward, backward, left, right. Maybe add a camera feed. The guide ends there.
The gap between "remote-controlled demo" and "autonomous machine" is not more powerful hardware. It is a control layer that can reason about goals, break them into motor sequences, read sensor data mid-task, and adjust when something goes wrong. That is what an AI agent provides, and it is why motor control and agent orchestration belong in the same conversation.
A Raspberry Pi cannot drive motors directly from its GPIO header. The Pi 5's pins operate at 3.3V logic with roughly 16 mA maximum per pin. Even a small hobby motor draws hundreds of milliamps at 5V or higher. Connecting a motor straight to GPIO will stall the motor at best and damage the board at worst. Every Pi motor project needs a driver circuit that sits between the GPIO signals and the motor's power supply.
Three motor types cover the majority of Pi robotics use cases:
- DC motors for continuous rotation (wheels, fans, pumps)
- Stepper motors for precise angular positioning (CNC axes, camera sliders, robot arms)
- Servos for controlled angle within a fixed range (grippers, pan-tilt heads, rudders)
Each type requires a different driver and a different control strategy. The sections below cover all three: how to choose between them, which driver hardware to buy, the Python code for each, and how to wire motor commands into an OpenClaw agent so the Pi can act on natural language instructions instead of waiting for keystrokes.
How to Choose Between DC, Stepper, and Servo Motors
DC Motors
DC motors spin continuously when voltage is applied. Reverse the polarity and the shaft reverses. Control speed with pulse-width modulation (PWM), which rapidly switches voltage on and off at varying duty cycles. A 50% duty cycle runs the motor at roughly half speed.
DC gear motors, the type bundled with most Pi chassis kits, add a gear train that reduces rotational speed and increases torque. A typical 6V DC gear motor turns at around 200 RPM with enough torque to move a small wheeled robot across a flat surface.
Best for: Wheels, continuous conveyors, fans, water pumps. Anything that needs continuous rotation at variable speed.
Typical specs: 3V to 12V operating range, 100 mA to 1A draw, $2 to $8 per motor.
Driver required: An H-bridge such as the L298N, DRV8833, or TB6612 (built into the Adafruit Motor HAT). The H-bridge lets you reverse polarity programmatically and inject PWM for speed control.
Stepper Motors
Stepper motors divide a full rotation into discrete steps. A standard NEMA 17 stepper has 200 steps per revolution, meaning 1.8 degrees per step. Energizing coils in sequence moves the shaft one step at a time. You always know the angular position without a feedback sensor because each step covers a fixed angle.
Micro-stepping subdivides each full step further. Half-stepping gives 400 positions per revolution. 1/16 micro-stepping gives 3,200 positions. The tradeoff is lower torque per micro-step and more demanding driver timing.
Best for: 3D printer axes, CNC routers, camera sliders, robot arm joints. Anything that needs repeatable angular accuracy without an encoder.
Typical specs: NEMA 17 is the standard size for Pi projects. 1.8 degrees per step, 12V, 350 mA to 2A, holding torque around 40 N·cm. $8 to $15 per motor.
Driver required: A dedicated stepper driver (A4988, DRV8825, TMC2209) for standalone boards, or the Adafruit Motor HAT which handles two steppers over I2C.
Servo Motors
A servo is a DC motor with a built-in feedback loop and gearbox. Send a PWM signal with a specific pulse width (typically 1 ms to 2 ms within a 20 ms period) and the servo rotates to the corresponding angle, usually within a 0 to 180 degree range. A built-in potentiometer provides position feedback, so the servo holds its angle until told otherwise.
Continuous-rotation servos sacrifice angular positioning for full rotation at variable speed. They behave more like geared DC motors with simpler wiring.
Best for: Robot arm joints, grippers, pan-tilt camera mounts, rudders. The built-in feedback means no external encoder is needed.
Typical specs: SG90 micro servo ($3, 1.8 kg·cm torque, 180 degrees). MG996R standard servo ($8, 10 kg·cm torque, 180 degrees). 4.8V to 6V power, PWM control at 50 Hz.
Driver options: Direct GPIO PWM works for one or two servos. A PCA9685-based Servo HAT ($17.50 from Adafruit) handles 16 servos simultaneously over I2C with 12-bit resolution.
Quick Comparison
DC motor: Continuous rotation, variable speed, no position feedback, cheapest option, simplest wiring. Choose when you need wheels or a pump.
Stepper motor: Discrete steps, precise positioning without encoders, higher cost, more complex wiring. Choose when you need repeatable angular accuracy.
Servo motor: Angle positioning with built-in feedback, limited range (usually 180 degrees), moderate cost, simple PWM control. Choose when you need a joint or hinge that holds a specific angle.
What Motor Driver Hardware to Use and How to Wire It
Three driver options cover the full range of Pi motor projects. Pick based on motor type, current requirements, and how many motors you need to run.
L298N Dual H-Bridge Module
The L298N is the cheapest entry point for DC motor control at $3 to $5 per board. It drives two DC motors independently with up to 2A continuous current per channel and 3A peak. Input voltage ranges from 5V to 35V, though 6V to 12V is the recommended range for most Pi projects.
The board uses six GPIO connections: four direction pins (IN1 through IN4) and two enable pins (ENA, ENB) for PWM speed control. That pin count is the main drawback. Each additional L298N consumes six more GPIO pins, and the Pi 5 only has 26 usable GPIO pins total.
Wiring summary:
- Motor A wires to OUT1 and OUT2 screw terminals
- Motor B wires to OUT3 and OUT4 screw terminals
- IN1 and IN2 connect to GPIO pins for Motor A direction
- IN3 and IN4 connect to GPIO pins for Motor B direction
- ENA connects to a PWM-capable GPIO pin for Motor A speed
- ENB connects to a PWM-capable GPIO pin for Motor B speed
- GND on the L298N connects to a Pi GND pin
- External battery (6V to 12V) connects to the power screw terminals
One detail to watch: the L298N uses internal bipolar transistors that drop approximately 2V across the H-bridge. A 6V battery delivers roughly 4V to the motors. Use a higher voltage supply or switch to a MOSFET-based driver like the DRV8833 if voltage drop matters for your application.
Adafruit DC and Stepper Motor HAT
The Adafruit Motor HAT (product 2348, $22.50) mounts directly on the Pi's 40-pin header and controls up to four DC motors or two stepper motors. It uses TB6612 MOSFET drivers instead of bipolar transistors, providing 1.2A continuous per channel with 3A peak bursts and noticeably lower voltage drop than the L298N.
Communication runs over I2C, requiring only SDA and SCL. That is two pins instead of six. The default I2C address is 0x60, and you can stack up to 32 Motor HATs by changing address jumpers, scaling to 128 DC motors or 64 steppers from the same two I2C pins.
Motor supply voltage ranges from 4.5V to 13.5V through dedicated screw terminals. The HAT includes polarity protection on the power input and built-in flyback diodes for back-EMF protection.
Install the Python library:
pip3 install adafruit-circuitpython-motorkit
Adafruit 16-Channel PWM Servo HAT
The Servo HAT (product 2327, $17.50) drives up to 16 servos from a single PCA9685 PWM controller chip. Each channel provides 12-bit resolution (4,096 steps) at a programmable PWM frequency up to 1.6 kHz. For standard servos, set the frequency to 50 Hz and control position by adjusting the pulse width per channel.
The HAT communicates over I2C and stacks up to 62 boards for a maximum of 992 servo channels, all from two GPIO pins.
Install the Python library:
pip3 install adafruit-circuitpython-servokit
Servos draw power from a separate V+ terminal on the HAT, not from the Pi's 5V rail. Use a 5V 2A or higher power supply. A single SG90 servo draws about 250 mA under load, so sixteen servos moving at once could pull 4A or more.
Store motor telemetry and calibration data across Pi build sessions
A workspace with automatic indexing. Your OpenClaw agent reads and writes files through MCP, and you review results from any browser. Starts with a 14-day free trial.
How to Set Up Python and Control Each Motor Type
All examples below assume Raspberry Pi OS (Bookworm or later) and Python 3.9+. If you are running a Pi 5, the legacy RPi.GPIO library does not support the Pi 5's RP1 I/O controller. Install rpi-lgpio as a drop-in replacement:
pip3 install rpi-lgpio
Do not install rpi-lgpio alongside RPi.GPIO. Both provide the same Python namespace and will conflict. Remove RPi.GPIO first if it is already installed.
DC Motor with the Motor HAT
import time
from adafruit_motorkit import MotorKit
kit = MotorKit()
kit.motor1.throttle = 1.0 # full speed forward
time.sleep(2)
kit.motor1.throttle = -0.5 # half speed reverse
time.sleep(2)
kit.motor1.throttle = 0 # brake to stop
The throttle property accepts values from -1.0 (full reverse) through 1.0 (full forward). Setting throttle to 0 brakes the motor. Setting it to None releases the motor so it coasts to a stop instead of actively braking.
Stepper Motor with the Motor HAT
import time
from adafruit_motorkit import MotorKit
from adafruit_motor import stepper
kit = MotorKit()
### One full revolution: 200 steps for a 1.8-degree stepper
for i in range(200):
kit.stepper1.onestep(
direction=stepper.FORWARD,
style=stepper.SINGLE
)
time.sleep(0.01)
### 100 micro-steps backward
for i in range(100):
kit.stepper1.onestep(
direction=stepper.BACKWARD,
style=stepper.MICROSTEP
)
time.sleep(0.005)
kit.stepper1.release() # de-energize coils when done
Four stepping styles are available: SINGLE (one coil at a time, lowest power draw), DOUBLE (two coils energized, higher torque), INTERLEAVE (alternating half-steps for smoother motion at half the speed), and MICROSTEP (1/16 steps, the smoothest motion but lowest torque per step).
Servo with the Servo HAT
from adafruit_servokit import ServoKit
kit = ServoKit(channels=16)
kit.servo[0].angle = 90 # center position
kit.servo[1].angle = 0 # minimum position
kit.servo[2].angle = 180 # maximum position
The angle property accepts values from 0 through the servo's maximum range (180 for most standard servos). For continuous rotation servos, use the throttle property instead:
kit.continuous_servo[3].throttle = 0.5 # half speed forward
kit.continuous_servo[3].throttle = -1.0 # full speed reverse
kit.continuous_servo[3].throttle = 0 # stop
Direct GPIO with gpiozero
For simple setups without a HAT, the gpiozero library (pre-installed on Raspberry Pi OS) provides high-level motor and servo classes:
from gpiozero import Motor, Servo
from time import sleep
motor = Motor(forward=17, backward=18)
motor.forward(speed=0.75)
sleep(2)
motor.reverse()
sleep(2)
motor.stop()
servo = Servo(25)
servo.min()
sleep(1)
servo.mid()
sleep(1)
servo.max()
gpiozero uses software PWM, which works for basic projects but causes visible jitter on servos under CPU load. For multi-servo builds, the PCA9685 Servo HAT with hardware PWM gives much steadier signals.
Building Agent-Controlled Motion with OpenClaw
Once motor control works in Python, the next step is connecting it to an agent that can reason about multi-step movement. OpenClaw, the open-source AI agent framework, treats motor commands as skills: individual Python functions that the agent calls based on natural language reasoning.
The ROSClaw framework (published March 2026, arXiv:2603.26997) formalizes this bridge between OpenClaw and ROS 2 for physical robot control. ROSClaw acts as a model-agnostic executive layer where any foundation model can perceive sensor data, reason about goals, and issue motor commands on ROS-enabled hardware. Researchers tested the framework on wheeled, quadruped, and humanoid platforms. They found that different foundation models exhibit up to 4.8x differences in out-of-policy action proposal rates, meaning the choice of model backend matters as much as the motor driver hardware when safety and precision are the goal.
For a Pi motor project that does not need a full ROS 2 stack, the integration pattern is simpler. You write a Python function for each motor operation (drive forward, rotate stepper, set servo angle), register it as an OpenClaw skill, and the agent calls the right function when reasoning about a movement task. Tell it "drive forward one meter, then pan the camera left 45 degrees" and the agent breaks that into sub-tasks: set DC motor throttle for the estimated distance, monitor a timer or encoder, stop, then set the servo angle.
The agent's reasoning loop follows a sense-decide-act pattern. Read sensor data (distance, orientation, current draw). Decide the next action based on the goal and current state. Execute the motor command. Check the result before continuing. If an ultrasonic sensor reports an obstacle closer than expected, the agent adjusts speed or reroutes. If a stepper stalls (detectable through current monitoring), the agent can back off and retry at lower speed.
ClawBody, a companion project documented alongside ROSClaw, provides a bridge to physical hardware with MuJoCo simulation support. This lets you test motor sequences in a physics simulation before running them on real hardware, reducing the risk of stripped gears or broken mounts during early development.
Storing Motor Data Beyond the Pi's SD Card
Robot builds generate data that outlives any single session: motor calibration parameters, sensor baselines, movement logs, skill execution history. Keeping everything on the Pi's microSD card works during prototyping, but SD cards wear out under frequent writes and the data stays locked on one machine.
Several options exist for offloading that data. A self-hosted InfluxDB instance handles time-series sensor data well. An S3 bucket provides cheap bulk storage for log archives. A workspace platform like Fast.io adds an intelligence layer on top of storage: upload calibration files after a tuning run, and they are indexed automatically for search and AI-powered queries through Intelligence Mode.
With Fast.io, the OpenClaw agent on your Pi reads and writes files through the MCP server over Streamable HTTP. Transfer the workspace to a teammate who picks up the build where you left off, with full audit history of every file change. Plans start with a 14-day free trial (Solo at $29/month, Business at $99/month), with storage, monthly credits, and workspaces scaled to each tier. For a Pi motor project generating a few megabytes of telemetry per session, that covers years of builds. If you prefer keeping everything on your LAN, a networked MQTT broker plus SQLite on a home server works with no external dependencies at all.
Frequently Asked Questions
How do I control a motor with Raspberry Pi?
Connect a motor driver between the Pi's GPIO pins and the motor. The Pi's GPIO operates at 3.3V with roughly 16 mA per pin, which cannot drive any motor directly. An L298N dual H-bridge module ($3 to $5) handles two DC motors at up to 2A each using six GPIO pins. For more motors or cleaner wiring, the Adafruit Motor HAT ($22.50) drives four DC motors or two steppers from just two I2C pins. Python libraries like gpiozero (pre-installed on Raspberry Pi OS) and adafruit-circuitpython-motorkit provide high-level speed and direction control functions.
What motor driver is best for Raspberry Pi?
It depends on motor type and count. For one or two DC motors on a budget, the L298N is cheapest at $3 to $5 and simplest to wire. For up to four DC motors or two steppers with I2C convenience, the Adafruit DC and Stepper Motor HAT ($22.50) uses TB6612 MOSFET drivers with lower voltage drop than the L298N. For servo projects, the Adafruit 16-Channel Servo HAT ($17.50) controls 16 servos with 12-bit PWM resolution over I2C. The DRV8833 is a solid alternative for low-voltage DC motors, and the A4988 or DRV8825 are the standard standalone stepper drivers for NEMA 17 motors.
Can Raspberry Pi control a stepper motor?
Yes. A NEMA 17 stepper (the standard size for Pi projects) connects through a dedicated driver. The Adafruit Motor HAT handles two steppers over I2C with single, double, interleave, and micro-stepping modes via the adafruit-circuitpython-motorkit Python library. Standalone driver boards like the A4988 or DRV8825 use GPIO pins for step and direction signals. Each full step moves the shaft 1.8 degrees (200 steps per revolution), and micro-stepping subdivides that further for smoother motion at the cost of reduced torque per step.
How do I control servo speed with Raspberry Pi?
Standard servos move to the target angle at their maximum speed and do not have built-in speed control. To slow a servo, step through intermediate angles with small delays between each step in your Python code. Moving from 0 to 90 degrees in 1-degree increments with a 20 ms delay between each creates a smooth sweep taking about 1.8 seconds. The adafruit-circuitpython-servokit library sets any angle from 0 to 180 on each of the Servo HAT's 16 channels. Continuous rotation servos do have speed control via the throttle property, where values from -1.0 to 1.0 set direction and speed simultaneously.
Related Resources
Store motor telemetry and calibration data across Pi build sessions
A workspace with automatic indexing. Your OpenClaw agent reads and writes files through MCP, and you review results from any browser. Starts with a 14-day free trial.