Skip to content

Why Robots Pair Raspberry Pi with ESP32: 2WD Mobile Robot Hardware Layers and Five Core Components

Learn why a Raspberry Pi 5 alone struggles with motor loops and how a 2WD robot splits sensors, actuators, and micro-ROS across four timing layers.

Contents

Key takeaways

  1. An autonomous mobile robot is a closed-loop system built from five core components—sensors, actuators, controllers, power, and frame—partitioned into four execution layers according to strict timing requirements.
  2. Because a Raspberry Pi 5 running standard Ubuntu Linux experiences multi-millisecond scheduling jitter, deterministic 200–1,000 Hz PWM and encoder PID loops belong on a microcontroller such as an ESP32-S3 bridged via micro-ROS.
  3. Sensor data bandwidth spans more than three orders of magnitude—from 14.4 kB/s for a 2D LiDAR to 27.6 MB/s for uncompressed 640×480 RGB video—requiring explicit onboard processing or compression boundaries before transmitting over WiFi.
  4. Differential-drive kinematics relate linear velocity v and angular velocity ω directly to wheel radius r and wheel separation L, making physical caliper measurements the ground truth for URDF links, joints, and TF frames.

An industrial autonomous mobile robot (AMR) hauling hundreds of kilograms across a warehouse floor and a compact educational rover rolling across a desk differ in component cost by two orders of magnitude. Yet the systems architecture governing their hardware and software integration is remarkably similar. Both partition hardware along a single primary axis: how quickly and deterministically each subsystem must respond to physical events. Components are grouped into timing tiers, and the boundaries between those tiers are standardized through message contracts and coordinate frames.

Once an engineering team has evaluated when to adopt ROS 2 in a Physical AI development roadmap, the very next requirement is decomposing the physical machine that will execute that code. Using the 2WD differential-drive mobile robot myros_sketch as a concrete reference design, this guide examines the five fundamental hardware subsystems of a robot, the four execution timing layers, the engineering rationale for pairing a Raspberry Pi 5 with an ESP32-S3 over micro-ROS, and the bandwidth and kinematic calculations that directly shape your URDF model.

Five Core Hardware Subsystems and Their Mapping to the ROS 2 Graph

A common pitfall when designing a first robot is treating the hardware bill of materials as an unstructured shopping list. A robot is not a loose collection of parts; it is a closed-loop physical system in which sensors measure state, controllers compute decisions, and actuators apply forces back to the environment, all supported by a rigid mechanical frame and a stable power delivery network. Every core abstraction described in the official ROS 2 Jazzy documentation—nodes, topics, parameters, actions, and TF2 coordinate transforms—maps directly onto one of these five physical subsystems.

Hardware SubsystemPhysical Role in the Closed Loopmyros_sketch Reference HardwareRepresentation in the ROS 2 Graph
SensorsMeasure external environment geometry and internal robot state2D 360° LiDAR, 6-axis IMU, USB RGB camera, quadrature wheel encodersPublisher nodes streaming typed messages (/scan, /imu/data, /camera/image_raw)
ActuatorsConvert electrical energy into mechanical torque and planar motionDual N20 geared DC motors, 65 mm drive wheels, front ball casterSubscriber control loop consuming /cmd_vel (geometry_msgs/msg/Twist)
ControllersExecute state estimation, path planning, and real-time motor PID loopsRaspberry Pi 5 (high-level compute) + ESP32-S3 (real-time MCU)ROS 2 nodes, runtime parameters, lifecycle states, and action servers
Power SystemSupply isolated, regulated voltage and peak current to all railsLi-ion/LiPo battery pack, separate buck regulators for motors and computeDiagnostics and battery telemetry topics (sensor_msgs/msg/BatteryState)
Frame & ChassisDefine rigid mounting geometry, load distribution, and coordinate origins3D-printed chassis plate (chassis), axle center (base_link), sensor mountsURDF <link> and <joint> elements published into the TF2 transform tree

Viewing hardware through this five-part table reveals why mechanical design and software architecture cannot be separated. A sensor is a topic publisher; a controller is a node; the physical chassis is the TF2 tree. If a sensor bracket flexes or a wheel separation measurement is off by a few millimeters, the resulting errors propagate directly into SLAM map alignment and navigation control.

The Four Execution Layers: High-Level Cognition Above, Real-Time Reflexes Below

When mapping those five subsystems onto physical processors, the decisive engineering constraint is cycle time and latency tolerance. Inside the same mobile robot, a camera frame arrives every 33.3 ms (30 Hz) and a 2D LiDAR revolution completes every 100 ms (10 Hz), whereas the wheel velocity PID loop must execute every 1 to 5 ms (200 to 1,000 Hz) and the H-bridge current switching runs at 10 to 20 kHz (50 to 100 µs). Forcing tasks whose timing demands differ by a factor of 1,000 onto a single general-purpose operating system causes priority inversion and scheduling jitter: a 1 ms motor loop ends up waiting behind a 30 ms image decoding task.

Execution LayerPrimary ResponsibilityRepresentative Hardware (myros_sketch)Target Update FrequencyConsequence of Layer Failure
PerceptionCapture obstacle distances, visual features, and inertial motion2D LiDAR, 6-axis MEMS IMU, USB camera10–100 Hz (10–100 ms)Map distortion, delayed obstacle detection
CognitionLocalization (SLAM), global path planning, local trajectory rolloutRaspberry Pi 5 (8 GB RAM, Ubuntu 24.04)10–50 Hz (20–100 ms)Failure to reach goal pose (robot halts safely)
Real-Time ControlWheel velocity PID tracking, encoder pulse counting, watchdog stopESP32-S3 (8 MB PSRAM, FreeRTOS)100–1,000 Hz (1–10 ms)Curved drift during straight travel, velocity oscillation
ActuationGenerate mechanical shaft torque against ground frictionN20 geared DC motors, 65 mm wheels, caster10–20 kHz PWM switchingRobot fails to move physically

Notice the structural split between the middle two rows: the cognition layer operates comfortably at tens of hertz, whereas the real-time control layer requires hundreds of hertz with minimal period variance. When evaluating compute modules using a robot edge AI SoC selection checklist, engineers prioritize TOPS, memory bandwidth, and thermal envelopes for high-level perception. At the real-time control tier, however, raw floating-point throughput matters far less than keeping timer jitter within a few tens of microseconds.

Why a Raspberry Pi 5 Should Not Drive Motors Directly

The Raspberry Pi 5 features a quad-core Arm Cortex-A76 processor running Ubuntu 24.04 LTS, making it well suited for running SLAM, Nav2, computer vision nodes, and DDS discovery simultaneously. Closed-loop motor control, by contrast, requires a deterministic execution period. If a velocity PID controller is tuned for a 200 Hz (5.00 ms) update rate, the standard deviation of the interval $\Delta t$ between consecutive updates must stay within tens of microseconds for wheel rotation to remain smooth.

When a developer connects an H-bridge motor driver directly to Raspberry Pi GPIO pins and runs a velocity loop in a standard Linux user-space process or Python script, several non-deterministic delays occur regularly:

  • Decoding a single camera frame or updating a 2D occupancy grid can preempt the control thread for 20 to 40 ms.
  • WiFi packet retransmissions and SD card or NVMe storage interrupts contend with GPIO interrupt handling, inflating latency jitter.
  • Python garbage collection pauses can double or triple a single control interval $\Delta t$, corrupting the derivative ($D$) and integral ($I$) terms of the discrete PID calculation.

When identical forward velocity commands are sent to the left and right wheels under those conditions, one wheel loop inevitably updates late or misses quadrature encoder edges, causing the robot to drift along a shallow arc instead of driving straight.

Comparison MetricRaspberry Pi 5 (High-Level Compute)ESP32-S3 (Real-Time Microcontroller)
Operating System / KernelUbuntu 24.04 Linux (non-real-time general scheduler)FreeRTOS (preemptive real-time scheduler)
PWM Signal GenerationSoftware timers or limited shared hardware channelsDedicated LEDC / MCPWM hardware timers (8+ channels)
Quadrature Encoder CountingOS interrupt latency risks dropped pulses at high RPMHardware Pulse Counter (PCNT) peripherals count without CPU load
Typical Power Draw3–5 W idle/moderate (8–12 W under peak load)0.3–0.5 W
Assigned RoleSLAM, Nav2 planning, camera processing, TF publishing200 Hz motor PID, encoder odometry integration, hardware watchdog

Splitting the architecture across both processors resolves the conflict cleanly. The Raspberry Pi 5 computes “where the robot body should move” and publishes a 20 Hz geometry_msgs/msg/Twist command on /cmd_vel containing linear velocity $v$ and angular velocity $\omega$. The ESP32-S3—connected to the ROS 2 graph through the micro-ROS microcontroller framework over UART or USB CDC—translates that body twist into target left and right wheel angular velocities ($\omega_L, \omega_R$) and regulates motor PWM at a strict 200 Hz. Rather than duplicating compute, the design separates the planning cortex (Raspberry Pi 5) from the reflexive spinal cord (ESP32-S3).

Sensor Layer: Managing a 1,000x Bandwidth Gap and Coordinate Conventions

Robotic sensors fall into two functional categories: exteroceptive sensors that measure the external world (2D LiDAR, RGB or depth cameras) and proprioceptive sensors that measure the robot’s internal physical state (IMU accelerometer and gyroscope, wheel encoders, battery monitors).

Two quantitative factors govern sensor integration in ROS 2: per-topic data bandwidth and spatial-temporal coordinate alignment. The table below details the exact message sizes and data rates for the sensor suite on myros_sketch.

Sensor / Data StreamROS 2 Message TypePublish RateSingle Payload SizeSustained Bandwidth
2D LiDAR (360° scan)sensor_msgs/msg/LaserScan10 Hz360 rays × 4 B ≈ 1.44 kB~14.4 kB/s
6-Axis IMUsensor_msgs/msg/Imu100 Hz~330 B (including 3×3 covariances)~33.0 kB/s
Wheel Encoderssensor_msgs/msg/JointState50 Hz~400 B (names, positions, velocities)~20.0 kB/s
Camera (640×480 RGB raw)sensor_msgs/msg/Image30 Hz640 × 480 × 3 B = 921.6 kB~27.6 MB/s
Camera (JPEG compressed)sensor_msgs/msg/CompressedImage15 Hz40–80 kB per frame~0.9 MB/s
Velocity Command (/cmd_vel)geometry_msgs/msg/Twist20 Hz6 × float64 = 48 B< 1.0 kB/s
# Verify real-time publish frequency, bandwidth consumption, and timestamp delay using ROS 2 CLI tools
ros2 topic hz /scan                  # Confirm the LiDAR driver maintains a steady ~10 Hz rate
ros2 topic bw /camera/image_raw      # Measure raw camera throughput (~27.6 MB/s uncompressed)
ros2 topic delay /scan               # Inspect header.stamp transport delay to spot network bottlenecks

A single uncompressed 640×480 camera stream at 30 Hz (~27.6 MB/s) consumes more than 400 times the combined bandwidth of the LiDAR, IMU, wheel encoders, and velocity command topics (~68 kB/s total). If an engineer streams raw /camera/image_raw messages over a shared WiFi link to a remote workstation running RViz2, the wireless channel queues up behind multi-megabyte video frames, delaying /scan and /cmd_vel packets by half a second or more. Raw image streams should therefore stay inside the Raspberry Pi 5 (processed locally via intra-process communication or shared memory, publishing only compact bounding-box or lane vectors), or be compressed via sensor_msgs/msg/CompressedImage at reduced frame rates before crossing WiFi.

Physical mounting geometry and axis conventions are equally critical. Under REP-0103 standard units and coordinate conventions, standard robot body frames (base_link, laser_frame, imu_link) use a right-handed coordinate system with $+X$ forward, $+Y$ left, and $+Z$ up. Camera optical frames (camera_link_optical), however, define $+Z$ pointing forward along the lens optical axis, $+X$ to the right, and $+Y$ downward. Furthermore, the 2D LiDAR must sit parallel to the floor so wall scans do not tilt into the ground plane, and the IMU should be mounted close to the robot’s rotational axis to minimize centripetal acceleration artifacts during rapid turns.

Actuation, Power, and Frame: Differential-Drive Kinematics and Mechanical Stability

A two-wheeled differential-drive chassis uses two independently driven coaxial wheels paired with one or two passive casters. By varying the speed and direction of just two DC motors, the robot can execute straight lines, arcs of any radius, and zero-radius rotations in place without a steering linkage.

Let $r$ denote the drive wheel radius, $L$ the distance between the left and right wheel contact points (track width or wheel separation), and $\omega_L, \omega_R$ ($\text{rad/s}$) the angular velocities of the left and right wheels. The forward linear velocity $v$ ($\text{m/s}$) and yaw angular velocity $\omega$ ($\text{rad/s}$) at the midpoint between the two wheels are governed by the forward kinematics equations:

v=r(ωR+ωL)2,ω=r(ωR−ωL)Lv = \frac{r(\omega_R + \omega_L)}{2}, \qquad \omega = \frac{r(\omega_R - \omega_L)}{L}

Inverting these two equations yields the inverse kinematics evaluated 200 times per second on the ESP32-S3: $\omega_R = (v + \omega L / 2) / r$ and $\omega_L = (v - \omega L / 2) / r$.

For our reference platform myros_sketch, physical caliper measurements give a wheel radius of $r = 0.0325\text{ m}$ (65 mm diameter) and a wheel separation of $L = 0.160\text{ m}$ (160 mm). Achieving a top forward speed of $v = 0.5\text{ m/s}$ requires each wheel to spin at $\omega = 0.5 / 0.0325 \approx 15.38\text{ rad/s}$, which converts to approximately $147\text{ rpm}$. Executing an in-place rotation at $\omega = 1.5\text{ rad/s}$ requires spinning the two wheels in opposite directions at $(1.5 \times 0.160 / 2) / 0.0325 \approx 3.69\text{ rad/s}$ (~35 rpm). Working through these two arithmetic steps immediately validates motor sizing: a 200 rpm N20 geared DC motor provides comfortable headroom above the 147 rpm requirement.

Two structural foundations keep this kinematic model valid in the real world:

  • Support Polygon and Caster Placement: Two coaxial wheels define only a line of contact. Because myros_sketch mounts the Raspberry Pi 5, 2D LiDAR, and USB camera toward the front of the chassis, the center of mass shifts forward of the drive axle. Placing a 25 mm passive ball caster at the front center forms a triangular support polygon that encloses the center of mass and prevents forward tipping. Omitting the caster’s <collision> geometry in URDF causes physics simulators like Gazebo to tip the chassis nose-down into the floor.
  • Canonical Base Frame Hierarchy (base_footprint → base_link → chassis): Following the ROS 2 URDF tutorials, base_footprint sits at ground level directly beneath the drive axle center, base_link sits at the midpoint between the two wheel hubs, and chassis represents the physical 3D-printed body plate.
  • Isolated Power Rails: DC motors draw 3 to 5 times their nominal current during rapid acceleration or wheel stall. Powering both the motor H-bridge and the Raspberry Pi 5 from an unisolated regulator causes voltage drops (brownouts) that reboot the Linux board mid-drive. Separate buck converters for the 5V/5A logic rail and the motor actuator rail are mandatory.

Three Integration Points Where Software Meets Hardware and Reference Specifications

Once a robot is assembled and wired, the ROS 2 software stack interfaces with the physical hardware at three exact boundaries:

  1. The Topic Interface Boundary: Sensor drivers publish /scan, /imu/data, and /camera/image_raw, while the low-level controller subscribes to /cmd_vel and publishes wheel odometry /odom.
  2. The Coordinate Transform (TF2 & URDF) Boundary: Answering “where is an obstacle detected 1.2 m in front of the LiDAR relative to the drive axle?” requires an unbroken chain of coordinate transforms generated from the URDF model by robot_state_publisher.
  3. The Hardware Control Abstraction Boundary (ros2_control / micro-ROS): High-level twist commands are converted into closed-loop joint velocity setpoints using the exact wheel radius, track width, and joint axis vectors declared in the robot description.

A URDF file is therefore not a decorative 3D mesh for visualization; it is a machine-readable physical contract shared by sensor fusion, SLAM, and motor controllers. If the wheel separation $L$ entered in your URDF or controller YAML differs from the physical caliper measurement by even 10 mm, rotational odometry will systematically overshoot or undershoot every turn.

The table below consolidates the baseline specifications of myros_sketch used across subsequent URDF modeling and ROS 2 configuration tutorials.

Specification ItemBaseline ValueEngineering & URDF Modeling Notes
Chassis Dimensions200 × 150 × 50 mm (L × W × H)3D-printed rectangular body plate (chassis link)
Drive Configuration2WD differential drive + front casterDual independent rear/mid drive wheels + front passive caster
Drive Wheels65 mm diameter ($r = 0.0325\text{ m}$), 26 mm widthTrack width (wheel separation) $L = 160\text{ mm}$ ($0.160\text{ m}$)
Front Caster25 mm diameter ball casterMounted at front bottom centerline for three-point stability
Maximum VelocitiesLinear $0.5\text{ m/s}$, angular $1.5\text{ rad/s}$~147 rpm wheel speed at top linear velocity (200 rpm N20 motors)
High-Level ComputerRaspberry Pi 5 (8 GB RAM)Runs Ubuntu 24.04 LTS and ROS 2 Jazzy Jalisco
Real-Time ControllerESP32-S3 (8 MB PSRAM)Runs FreeRTOS + micro-ROS client with a 200 Hz velocity PID loop
2D LiDAR Sensor360° planar scan, 10 Hz, 0.15–12 m rangeScan plane elevated ~117 mm above ground (laser_frame)
IMU Sensor6-axis MEMS accelerometer + gyro, 100 HzMounted on top deck forward of axle center (imu_link)
Vision CameraUSB RGB camera, 640×480 @ 30 fpsMounted at front top edge (camera_link → camera_link_optical)
Total Mass~0.9 kg (excluding battery pack)Baseline mass for URDF <inertial> tensor calculations

While hardware architecture partitions a robot by execution timing and physical geometry, the software middleware layer partitions the system by distributed discovery and quality-of-service contracts. In the next installment, Why the ROS 1 Master Disappeared: ROS 2 Jazzy DDS Architecture and RMW Layer, we examine why ROS 2 replaced roscore with Data Distribution Service (DDS) discovery, how domain IDs map to UDP ports, and how QoS policies keep sensor and command streams reliable across wireless links.

Common mistakes

  • Wiring a motor driver directly to Raspberry Pi GPIO pins with software-timed PWM, which causes the robot to veer off course whenever camera decoding or disk I/O introduces scheduling jitter.
  • Streaming raw 30 fps camera frames over WiFi alongside LiDAR scans and velocity commands, saturating wireless bandwidth and delaying obstacle avoidance by hundreds of milliseconds.
  • Selecting motors and wheels based solely on nominal speed while ignoring stall current spikes, voltage brownouts on the compute rail, encoder resolution, and center-of-mass stability.

Pre-flight checklist

  • Have you fixed the physical transport link (UART, USB CDC, or WiFi UDP) and target control frequency (100–1,000 Hz) between the main compute board and the MCU?
  • Have you multiplied message size by publish rate for every sensor to calculate per-topic bandwidth and decided which streams stay local or require compression?
  • Have you measured wheel radius (r), wheel separation (L), caster offset, and sensor mounting heights in millimeters so CAD drawings and URDF parameters match exactly?
  • Have you separated the motor power rail from the 5V compute regulator rail so motor stall current peaks cannot brown out the Raspberry Pi 5?
  • Do both hardware and firmware implement an immediate safe-stop watchdog that cuts motor torque if velocity command packets stop arriving or battery voltage drops?

Frequently asked questions

Can a Raspberry Pi 5 run a 2WD robot by itself without an external microcontroller?
For slow open-loop motion, a single-board computer can toggle GPIO pins directly, but its limits appear immediately once closed-loop encoder PID and safety watchdogs are required. Standard Linux kernels introduce several milliseconds to tens of milliseconds of scheduling jitter during image processing, network interrupts, or Python garbage collection. Offloading the high-frequency motor and encoder loop to an ESP32-S3 guarantees deterministic cycle timing regardless of CPU load on the Raspberry Pi.
How does an ESP32-S3 microcontroller participate in a ROS 2 Jazzy computation graph?
The ESP32-S3 runs a lightweight micro-ROS client library over FreeRTOS and communicates via UART, USB CDC, or UDP with a micro-ROS agent process running on the Raspberry Pi 5. The agent translates XRCE-DDS packets into standard DDS discovery and pub/sub traffic, so nodes hosted on the microcontroller appear in the ROS 2 graph just like native Linux nodes.
Is a single 2D LiDAR sensor enough for indoor autonomous navigation?
In flat indoor corridors and rooms, a 360-degree 2D LiDAR provides sufficient range data for 2D SLAM and local obstacle avoidance. However, glass doors, mirrors, and matte-black surfaces scatter or absorb laser pulses, and obstacles below or above the single scan plane remain invisible. Combining the 2D LiDAR with an IMU for angular velocity fusion and a camera or bumper sensor for 3D hazard detection is standard engineering practice.

Sources & verification

  1. ROS 2 Jazzy Documentation — Concepts
  2. micro-ROS — Bringing ROS 2 to Microcontrollers
  3. REP-0103 — Standard Units of Measure and Coordinate Conventions
  4. ROS 2 Jazzy — URDF Tutorials

Last verified: