Skip to content
Home
Embedded Robotics: Microcontrollers, RTOS, Hardware Control

Embedded Robotics: Microcontrollers, RTOS, Hardware Control

Robotics Robotics 8 min read 1696 words Beginner ExcellentWiki Editorial Team

Robots are physical systems, and the software that drives them runs on embedded hardware — microcontrollers handling time-critical tasks like motor control, sensor reading, and communication at microsecond precision. Understanding embedded robotics is essential for anyone building robots that must interact reliably with the real world. This guide covers microcontroller selection, real-time operating systems (RTOS), sensor driver development, motor control, memory management, and hardware integration patterns drawn from production robotic systems.

Embedded Systems in Robotics

An embedded system in robotics typically consists of one or more microcontrollers communicating with a more powerful application processor. The microcontroller handles hard real-time tasks — reading encoders at 100 kHz, running PID loops at 1–10 kHz, generating PWM signals for motor drivers. The application processor runs ROS, computer vision, mission planning, and user interfaces, communicating with the microcontroller over UART, SPI, or USB.

This separation of concerns is deliberate. Microcontrollers provide deterministic timing essential for control stability, while application processors offer the memory and computational throughput needed for perception and planning. The Robot Operating System (ROS) standardizes communication between these layers through hardware drivers that bridge serial protocols to ROS topics. For production systems, the two-chip architecture also provides safety isolation — a fault on the application processor does not directly affect the real-time control loop.

The choice of microcontroller platform depends on the robot’s real-time requirements, peripheral needs, and ecosystem support. STM32-based boards dominate professional robotics due to their wide performance range from Cortex-M0 to dual-core Cortex-M7, extensive peripheral set, and mature HAL (Hardware Abstraction Layer). ESP32 has gained popularity for IoT-connected robots due to its built-in Wi-Fi, Bluetooth, and dual-core architecture. Teensy boards offer exceptional compatibility with Arduino libraries while providing Cortex-M4 and M7 performance.

Microcontroller Selection

STM32 microcontrollers from STMicroelectronics cover the entire spectrum from low-power Cortex-M0 devices at under a dollar to Cortex-M7 processors exceeding 600 MHz with hardware floating-point units and double-precision FPU. The STM32F4 and STM32H7 series are most common in robotics applications, offering multiple timers, ADCs with 12–16 bit resolution, CAN FD bus interfaces, and hardware quadrature encoder interfaces with timer capture/compare channels.

Selection criteria include: required PWM channels (typically 4–6 per motor), timer resolution for encoder reading (32-bit timers prevent rollover in long-duration operations), ADC channels and sampling rate for analog sensors, communication interfaces for peripherals, and available Flash/RAM for the control firmware. For a differential-drive robot with two motors, four quadrature encoders, an IMU, and a LiDAR, an STM32F405 provides adequate headroom at approximately $5 in quantity. For vision-guided robots requiring camera interfacing at the MCU level, the STM32H7 with its hardware JPEG encoder and DCMI camera interface provides a better fit.

The Arduino ecosystem, built around the ATmega328 and RP2040, remains popular for prototyping and educational robotics. The extensive shield ecosystem and library support reduce development time, but limited computational resources and 8-bit architecture constrain control loop frequency and sensor throughput. For production robotics, a migration path from Arduino to STM32 or ESP32 is common as requirements grow.

Real-Time Operating Systems

A real-time operating system (RTOS) provides deterministic task scheduling with predictable worst-case execution times — essential for robotic control. FreeRTOS is the most widely adopted RTOS in robotics, supporting 40+ microcontroller architectures with a minimal footprint (4–12 KB). Amazon’s acquisition and ongoing maintenance of FreeRTOS added over-the-air update support and standardized IoT connectivity.

FreeRTOS schedules tasks by priority with round-robin among equal-priority tasks. In a typical robot firmware architecture, priority assignment follows: highest priority for the motor control PID loop (1–10 kHz rate), medium priority for sensor reading and state estimation (100 Hz), lower priority for communication and logging (10–50 Hz). Interrupt service routines (ISRs) handle the most time-critical operations — encoder edge detection at microsecond precision — with minimal processing in the ISR and deferred work in RTOS tasks. Barry provides the definitive reference on FreeRTOS internals and application design (Barry, Mastering the FreeRTOS Real Time Kernel, Real Time Engineers Ltd., 2016).

FreeRTOS also provides queues for inter-task communication, semaphores for resource sharing, and software timers for periodic callbacks. The queue mechanism is fundamental for robotics firmware: sensor tasks write data to queues, the state estimator reads from sensor queues and writes estimated state to an output queue, and the control task reads from the state queue to compute actuator commands.

STM32CubeIDE integrates FreeRTOS seamlessly. The configurator generates initialization code with tasks, queues, and timers specified through a graphical interface. Zephyr RTOS is an alternative gaining traction, offering a more modern codebase, built-in driver frameworks, and support for memory protection units on Cortex-M devices.

Memory Management in Embedded RTOS

Memory management on microcontrollers differs fundamentally from application processors. Without MMU hardware, there is no virtual memory — all code and data addresses are physical. Stack overflow in an RTOS task can silently corrupt adjacent memory, causing intermittent failures that are notoriously difficult to debug.

Static memory allocation is preferred in safety-critical robotics firmware. All tasks, queues, and semaphores are created at system initialization rather than dynamically at runtime. This approach eliminates heap fragmentation and guarantees that memory allocation failures occur at boot rather than during operation. When dynamic allocation is unavoidable — for variable-length sensor messages — dedicated memory pools with fixed-size blocks prevent fragmentation.

Worst-case execution time (WCET) analysis verifies that all control loops meet their deadlines. Tools like the AbsInt aiT WCET analyzer compute guaranteed upper bounds on execution time by analyzing the binary code path. For less critical applications, empirical measurement with oscilloscope probing of GPIO toggles at task boundaries provides practical timing validation.

Sensor Driver Development

Sensor driver firmware must initialize the sensor, configure its operating mode, read measurements at the required rate, and handle communication errors. I²C and SPI are the dominant protocols for robotic sensors.

I²C uses two wires (SDA, SCL) and supports multiple devices on a shared bus with 7-bit or 10-bit addressing. A typical IMU such as the ICM-20948 on I²C provides accelerometer, gyroscope, and magnetometer readings at up to 1 kHz. The driver must handle bus arbitration, acknowledge bit checking, and multi-byte register read sequences. STM32 HAL provides interrupt-driven and DMA-based I²C to minimize CPU overhead during sensor reading.

SPI offers higher bandwidth at the cost of more pins (MISO, MOSI, SCK, CS per device). External ADCs and high-speed IMUs use SPI for the 10+ MHz data rates needed for high-frequency sensor fusion. SPI drivers manage chip select timing, clock polarity and phase configuration, and full-duplex data transfer.

Robust sensor drivers implement initialization retry with timeout, detect communication failures by verifying expected sensor identification registers, and report data quality flags to higher-level software. Circular buffers decouple sensor reading from processing, preventing data loss when the processor misses a sensor interrupt.

Motor Control and Actuator Interfaces

PID control is the workhorse of robotic motor control. The firmware PID loop reads current velocity or position from encoders, computes error relative to setpoint, and outputs a control signal to the motor driver. With an RTOS, the PID task runs at fixed priority and period, ensuring consistent control.

Encoder reading requires careful handling in firmware. Quadrature encoders produce two phase-shifted signals that encode both position and direction. Hardware timers with encoder mode — available on STM32 and Teensy — automatically count encoder edges without CPU intervention. For motors without encoders, back-EMF sensing or Hall effect sensors provide velocity feedback at lower resolution.

Brushless DC (BLDC) motor control requires six-step commutation or field-oriented control (FOC). FOC provides higher efficiency and smoother torque control by transforming three-phase currents into orthogonal d-q components. Implementation requires a fast ADC reading phase currents, a current control loop at 10–20 kHz, and space vector PWM generation. The SimpleFOC library provides an open-source FOC implementation for Arduino and STM32.

Hardware Integration and PCB Design

Building the complete embedded system involves integrating the microcontroller board, motor drivers, power management, sensors, and communication interfaces onto a unified platform. PCB design for robotics considers motor noise isolation — motor currents draw spikes that couple into sensor analog signals through shared ground and power traces. Separate analog and digital ground planes with a single star connection point minimize interference. Decoupling capacitors at each IC’s power pins filter high-frequency switching noise.

Power management must handle the disparity between logic voltage (3.3V or 5V) and motor voltage (12V–48V). A battery management system (BMS) protects lithium batteries from over-discharge, over-current, and cell imbalance. Voltage regulators with sufficient headroom and heat dissipation prevent brownouts under motor load.

FAQ

Why use an RTOS instead of a super-loop on a microcontroller?

An RTOS provides deterministic scheduling, priority-based preemption, and cleaner inter-task communication. For robots running control loops at multiple frequencies, an RTOS ensures the high-priority PID loop runs on time regardless of lower-priority tasks. Super-loops require manual timing management and cannot guarantee deadlines.

What is the best microcontroller for a beginner robotics project?

The Teensy 4.0 (Cortex-M7 at 600 MHz) offers exceptional performance with Arduino-compatible libraries at $24. For a lower-cost entry, the Raspberry Pi Pico (RP2040, $4) provides dual-core Cortex-M0+ with good documentation and a maturing ecosystem.

Can I run ROS directly on a microcontroller?

ROS 2 runs on microcontrollers via micro-ROS, which implements the standard ROS 2 client API with minimal memory footprint. However, for full ROS capabilities, most robots use a two-chip architecture with ROS on an application processor and micro-ROS or a serial bridge on the microcontroller.

How fast should my control loop run?

Wheel velocity control loops typically run at 100 Hz to 1 kHz for stable PID control. Higher frequencies provide smoother control but require faster sensor reading. Balancing loops for inverted pendulum robots need 1–5 kHz. The Nyquist criterion requires the control loop to run at least twice the bandwidth of the system dynamics.

How do I handle sensor noise in embedded firmware?

Apply low-pass filters on sensor readings (exponential moving average works well for moderate noise), use median filters for outlier rejection in rangefinder data, and implement sensor fusion with EKF or complementary filters to combine multiple noisy measurements into a cleaner estimate.


Related: See the sensors and actuators guide for detailed hardware interfacing patterns and component selection. Learn about robot simulation for testing firmware in a safe environment. Explore the robotics software architecture guide for integrating embedded firmware with higher-level software.

Section: Robotics 1696 words 8 min read Beginner 756 articles in section Report inaccuracy Back to top