STATERA Library · Series 08 · Volume 02 · Chapter 12 · EN
Source: https://github.com/Statera-Library/08_Vol_02_Embedded_Software_Engineering/blob/main/02_12_Embedded_Case_Studies/02_12_Embedded_Case_Studies_EN.md

Volume 02 Embedded Software Engineering

12. Embedded Case Studies

12.01 Indoor AMR Main Compute Board Embedded SW Design

An indoor Autonomous Mobile Robot (AMR) main compute board serves as the embedded computing center that connects perception, localization, navigation, communication, diagnostics, and supervisory control. Unlike a simple motor controller, it must coordinate heterogeneous workloads while maintaining predictable interfaces with safety controllers and low-level actuators. Its software architecture therefore emphasizes clear responsibility boundaries, deterministic data paths, fault containment, and maintainability throughout the robot lifecycle.

A practical main compute platform commonly combines a multicore CPU with hardware acceleration for vision or neural-network inference, high-speed memory, nonvolatile storage, and multiple industrial communication interfaces. Ethernet connects LiDAR, cameras, fleet infrastructure, and service equipment, while CAN, CAN-FD, RS-485, or EtherCAT may connect motor drives and distributed controllers. USB, PCIe, GPIO, UART, and I2C provide additional interfaces for sensors, expansion modules, and board-level management devices.

The embedded software stack should separate hardware-dependent functions from robot applications. Boot firmware initializes the processor, memory, storage, security mechanisms, and essential peripherals before transferring control to the operating system. Linux then provides device management, networking, process isolation, memory management, and system services. Board-support packages and device drivers expose hardware through stable interfaces so that localization, navigation, and perception software remain largely independent of specific board revisions.

Boot behavior is particularly important because an AMR must reach an operational state predictably after power-on, brownout recovery, or watchdog reset. The bootloader should validate software images, identify the active system partition, and support recovery when an update fails. System services should start according to explicit dependencies rather than arbitrary timing assumptions. Hardware initialization, network availability, sensor discovery, middleware startup, localization, navigation, and mission readiness can consequently progress through controlled system states.

Device drivers form the boundary between physical devices and higher-level robot software. Camera drivers may use V4L2, CAN devices can use SocketCAN, and Ethernet sensors generally communicate through vendor protocols or standardized network interfaces. Driver design should avoid unnecessary copies and blocking operations in high-rate paths. DMA, interrupt moderation, asynchronous I/O, bounded queues, and timestamp preservation become important when several cameras, LiDAR streams, encoders, and control messages operate simultaneously.

Time synchronization must be treated as a system-level requirement rather than a sensor-specific feature. Localization and sensor fusion depend on consistent timestamps across LiDAR, cameras, IMUs, wheel encoders, and external positioning sources. The compute board should maintain a clearly defined time domain and distribute or receive synchronization through mechanisms such as PTP when required. Software components should preserve acquisition timestamps instead of replacing them with arbitrary processing times later in the pipeline.

Real-time requirements on the main computer differ from those of dedicated motor-control MCUs. High-frequency current or velocity loops are normally executed closer to the actuator, while the main computer handles localization, trajectory generation, velocity commands, and supervisory logic at lower frequencies. PREEMPT_RT, CPU affinity, IRQ affinity, memory locking, and priority-controlled threads can nevertheless reduce scheduling jitter for critical communication and motion-related processes without forcing every application into a hard real-time model.

The architecture should explicitly separate safety-critical control from computationally intensive autonomy. Emergency-stop circuits, safety scanners, drive-enable signals, and safety-rated motion functions should not depend solely on a complex Linux application remaining healthy. The main computer can request motion and monitor safety status, but independent safety hardware or controllers should retain authority to inhibit hazardous movement. This separation prevents a navigation crash, GPU failure, or operating-system fault from becoming the only barrier against unsafe motion.

Perception workloads place different demands on the board. Camera decoding, object detection, semantic processing, and other AI functions may execute on a GPU, NPU, or dedicated accelerator, while CPU resources remain available for localization, navigation, middleware, networking, and diagnostics. Memory bandwidth must be considered alongside raw compute performance because copying large image tensors between processes can become a bottleneck. Shared memory, zero-copy transport, hardware decoding, and accelerator-aware buffers can substantially reduce unnecessary data movement.

Localization and navigation software require carefully controlled communication with sensors and actuators. LiDAR scans, IMU measurements, wheel odometry, and map information flow toward localization and environmental representation, while planned trajectories and velocity references flow toward drive controllers. Interfaces should define message units, coordinate frames, timestamp semantics, valid ranges, sequence behavior, and timeout handling. These contracts make failures observable and prevent ambiguous assumptions from spreading between software modules.

Process supervision is essential because an indoor AMR may operate continuously without an engineer nearby. Critical services should expose health information including execution state, update rate, communication latency, queue utilization, temperature, memory consumption, and error counters. A supervisory component can detect stalled processes, missing sensor streams, corrupted communication, or excessive resource consumption. Restart policies should distinguish recoverable application faults from conditions requiring controlled robot shutdown or complete system reboot.

Resource isolation prevents one workload from destabilizing the entire robot. CPU affinity and scheduling policies can reserve execution capacity for motion-related tasks, while perception and logging workloads use separate cores where practical. Memory limits, container boundaries, cgroups, and service-level restrictions can prevent runaway applications from exhausting system resources. Storage partitions should similarly separate the operating system, application software, maps, logs, temporary data, and update images so that excessive logging cannot make the root filesystem unusable.

Thermal and power management must be integrated with software because compute performance changes with temperature and available electrical power. Board sensors should monitor processor temperature, accelerator temperature, supply voltage, storage health, and fan operation. Rather than waiting for uncontrolled thermal throttling, the system can reduce noncritical AI workloads, camera processing rates, or background tasks when thermal margins shrink. Persistent abnormal conditions should be reported to robot diagnostics and reflected in operational readiness decisions.

The main compute board should also implement a structured diagnostic framework. Logs need consistent timestamps, severity levels, component identifiers, and fault codes so that failures can be reconstructed after deployment. High-volume sensor data should not be logged indiscriminately; instead, event-triggered recording and bounded ring buffers can preserve data surrounding collisions, localization loss, emergency stops, or unexpected resets. Persistent crash information should survive reboot and remain available for maintenance analysis.

Security begins before normal applications execute. Secure boot can establish trust from immutable hardware or firmware through the bootloader, kernel, and application environment. Signed software packages, protected credentials, restricted administrative interfaces, authenticated communication, and least-privilege services reduce the attack surface. Network interfaces intended for maintenance should not automatically provide unrestricted access to robot control functions, and security credentials should be managed independently from application source code.

OTA capability should be designed into the storage and boot architecture rather than added after deployment. An A/B system layout allows a new image to be written to an inactive partition while the robot continues using the known-good version. After verification, the bootloader can attempt the new system and automatically roll back if health checks fail. Application compatibility, configuration migration, firmware dependencies, and communication protocol versions must also be managed because updating only the Linux image does not guarantee system-level compatibility.

Hardware watchdogs provide another layer of recovery when software supervision itself becomes unavailable. A watchdog should be serviced only when essential system health conditions are satisfied, rather than blindly refreshed by an independent timer thread. If critical execution stops, the watchdog can reset the compute board while the safety controller maintains the robot in a nonhazardous condition. Reset causes, boot counters, and preceding diagnostic information should be retained whenever possible to distinguish software hangs from power or hardware failures.

Development and validation should reproduce the hardware interfaces without requiring a complete robot for every test. Mock drivers, recorded sensor streams, software-in-the-loop environments, and hardware-in-the-loop benches allow navigation and supervisory components to be exercised systematically. Driver-level tests can verify timeout behavior, corrupted frames, disconnections, and high-load conditions, while long-duration tests expose memory leaks, storage growth, thermal problems, race conditions, and timing degradation that short functional tests often miss.

Configuration management becomes increasingly important when one compute-board design supports several AMR variants. Hardware revision, sensor configuration, calibration, network topology, robot identity, and feature options should be represented explicitly rather than embedded as scattered constants. Versioned configuration schemas allow software to detect incompatible parameters during startup. Factory defaults, deployment-specific settings, calibration data, and runtime state should remain logically separated so that software updates do not unintentionally overwrite robot-specific information.

The resulting embedded design is therefore not merely a Linux computer installed inside an AMR. It is a managed execution platform connecting high-bandwidth perception, deterministic robot communication, accelerated computation, safety supervision, diagnostics, security, and lifecycle services. By combining layered hardware abstraction, bounded real-time paths, independent safety authority, resource isolation, secure boot, watchdog recovery, and rollback-capable OTA, the main compute board can support reliable indoor autonomous operation while remaining maintainable as sensors, algorithms, and hardware evolve.

12.02 Outdoor AMR Motor Controller Firmware Case

An outdoor Autonomous Mobile Robot (AMR) motor controller is a dedicated embedded subsystem responsible for converting high-level motion commands into deterministic electrical control of traction and steering actuators. Unlike the main compute board, which performs perception and navigation, the motor controller operates close to the physical drivetrain. Its firmware must therefore prioritize predictable timing, rapid fault response, actuator protection, communication integrity, and safe behavior under harsh outdoor operating conditions.

A representative outdoor AMR may use independent traction motors, differential drive, Ackermann steering, or combinations of propulsion and steering actuators depending on vehicle size and mobility requirements. Each motor controller receives velocity, torque, steering, or enable commands from the supervisory computer and converts them into PWM signals or commands for power electronics. Encoder, current, voltage, temperature, and position feedback continuously close the control loops around the physical drivetrain.

The firmware architecture is commonly divided into hardware abstraction, peripheral drivers, control services, communication services, safety supervision, diagnostics, and application-level state management. Hardware-dependent register operations should remain isolated within a Hardware Abstraction Layer (HAL), allowing control algorithms to remain portable across MCU variants. This separation also simplifies unit testing and makes future replacement of gate drivers, encoders, current sensors, or communication transceivers less disruptive.

A high-performance microcontroller such as an ARM Cortex-M class device can provide timers, ADC channels, DMA engines, communication peripherals, watchdogs, and sufficient computational performance for motor control. Hardware timers generate precise PWM waveforms, while synchronized ADC triggering samples motor currents and supply voltages at controlled positions within switching cycles. DMA can transfer repetitive measurements with minimal CPU intervention, reducing interrupt overhead and improving control-loop timing consistency.

Firmware execution should be organized around clearly defined timing domains. Fast current or torque loops may operate at several kilohertz or higher, while velocity control executes at a lower rate and vehicle-level command processing operates more slowly. Diagnostics, temperature monitoring, logging, and communication management can run in background tasks. Separating these rates prevents noncritical activities from introducing excessive jitter into control loops whose timing directly affects motor stability and response.

Interrupt design is consequently central to the implementation. High-priority timer and ADC interrupts should perform only bounded operations required by the control loop, avoiding blocking communication, dynamic memory allocation, or lengthy diagnostic processing. Lower-priority interrupts and scheduled tasks can process CAN messages, update telemetry, and store diagnostic information. Execution-time measurements should confirm that worst-case interrupt latency remains safely below the control-period deadline under maximum system load.

The control pipeline begins with sensor acquisition and signal conditioning. Encoder counts are converted into wheel velocity or steering position, while ADC measurements provide phase current, DC bus voltage, motor temperature, and other electrical quantities. Raw measurements may require calibration, offset correction, scaling, filtering, and plausibility checks before entering the controller. Invalid or physically impossible measurements should be detected explicitly rather than propagated into torque or velocity calculations.

For traction control, the firmware can implement cascaded control loops in which an outer velocity controller generates a torque or current reference and an inner controller regulates actuator current. Depending on the motor and drive architecture, Field-Oriented Control (FOC) may transform measured phase currents into rotating reference coordinates and regulate torque-producing and flux-producing components independently. PWM generation then converts the controller output into switching commands for the inverter power stage.

Steering control requires similar attention to mechanical limits and feedback validity. A steering actuator may use encoder position feedback with position and velocity loops, while firmware enforces maximum steering angle, steering rate, motor current, and mechanical travel boundaries. Limit switches or independent position references can provide additional protection. When commanded and measured steering positions diverge beyond an allowable tolerance, the controller should report a fault rather than continuously increasing actuator effort.

Communication with the main compute system commonly uses CAN, CAN-FD, EtherCAT, or industrial Ethernet depending on vehicle architecture. Command messages should contain clearly defined units, ranges, sequence information, and timeout behavior. The controller must never assume that the last valid command remains safe indefinitely. If new motion commands stop arriving within the configured supervision interval, firmware should transition toward a defined controlled-stop or disabled state according to the system safety concept.

A robust communication layer validates message identifiers, payload lengths, checksums where applicable, command ranges, sequence counters, and communication freshness. Received values should pass through an interface layer before reaching control algorithms so malformed network data cannot directly manipulate hardware. Transmitted status frames can include actual velocity, steering position, motor current, bus voltage, temperature, operating state, fault bits, warning bits, and controller software version for supervisory monitoring.

The controller state machine provides a deterministic framework for managing startup and operation. Typical logical states include initialization, self-test, disabled, ready, enabled, running, controlled stopping, fault, and recovery. Transitions should occur only when explicit conditions are satisfied. For example, motor output must remain disabled until sensor validity, supply voltage, communication status, safety inputs, and internal diagnostics confirm that activation is permissible.

Safety-related inputs require a path that remains effective even when normal application processing fails. Emergency-stop status, drive-enable signals, external safety-controller outputs, and power-stage fault inputs should be monitored using appropriate hardware and firmware mechanisms. Where the safety architecture requires it, power-stage inhibition must not depend exclusively on software. Firmware participates by recognizing the event immediately, suppressing torque commands, recording the cause, and reporting the resulting safe state.

Electrical protection is particularly important for outdoor AMRs because terrain, payload, slopes, wheel obstruction, and impacts can produce severe transient loads. Firmware should supervise overcurrent, overvoltage, undervoltage, motor temperature, inverter temperature, encoder failure, stalled rotor conditions, and excessive command tracking error. Thresholds may include warning and shutdown levels so that performance can be reduced before a condition becomes severe enough to require immediate actuator disablement.

Outdoor environments introduce additional disturbances that should influence firmware design. Wheel slip, vibration, water exposure, large temperature variations, electromagnetic interference, and supply-voltage fluctuations can create noisy measurements or intermittent communication. Filtering must reduce noise without introducing excessive control delay. Sensor plausibility logic should distinguish short disturbances from persistent faults, while repeated abnormal events should accumulate diagnostic evidence that can be examined during maintenance.

Fault handling should distinguish recoverable, latched, and safety-critical conditions. A temporary communication disturbance might allow controlled recovery after valid messages return, whereas severe overcurrent or gate-driver faults may require output shutdown and an explicit reset procedure. Automatic recovery should never create repeated uncontrolled enable-disable cycles. Each fault should therefore define its detection criterion, immediate reaction, persistence behavior, recovery condition, and diagnostic record.

Watchdog supervision provides protection against firmware deadlock or runaway execution. A hardware watchdog should be refreshed only after critical tasks demonstrate successful execution within their expected periods. If the main control loop, communication supervision, or safety monitoring stops progressing, the watchdog eventually resets the MCU. After reset, outputs must remain inactive until initialization and safety checks complete, preventing an uncontrolled restart from immediately producing motor torque.

Nonvolatile diagnostic storage can preserve reset causes, accumulated operating hours, critical fault counters, maximum observed temperatures, overcurrent events, and selected lifecycle information. Flash writes should be controlled to prevent excessive wear, especially when faults occur repeatedly. Important event records can be buffered in RAM and committed only when necessary, while wear-leveling or dedicated storage regions can extend service life for long-running industrial robots.

Bootloader and firmware update design must preserve drivetrain safety during maintenance. Firmware images should be authenticated before execution, and interrupted updates must not leave the controller in an uncontrolled state. Dual-image or recovery-capable boot strategies can preserve a known-good version. Compatibility between motor-controller firmware and the main computer should also be checked because changes in command scaling, message definitions, or state-machine behavior can otherwise produce hazardous integration errors.

Testing should extend beyond nominal motor operation. Unit tests can verify conversion functions, state transitions, saturation logic, fault handling, and communication parsing, while Hardware-in-the-Loop (HIL) testing can emulate encoders, currents, voltages, communication loss, and power-stage faults. Dynamometer and vehicle testing can then evaluate acceleration, braking, steering response, thermal behavior, slope operation, wheel obstruction, emergency stopping, and long-duration reliability under realistic mechanical loads.

The resulting outdoor AMR motor-controller firmware acts as the deterministic bridge between autonomous decision software and physical motion. Its quality depends not only on the control algorithm but also on timing architecture, sensor validation, communication supervision, state management, protection logic, watchdog recovery, secure updating, and systematic diagnostics. When these mechanisms are designed together, the controller can deliver responsive motion while ensuring that communication failures, environmental disturbances, software faults, and electrical abnormalities lead to controlled and diagnosable behavior.

12.03 Mobile Manipulator EtherCAT Master Embedded Design

A mobile manipulator combines an autonomous mobile base with a multi-axis robotic arm, creating an embedded control problem that requires coordinated mobility and manipulation. The EtherCAT master becomes the deterministic communication backbone between the main controller and distributed servo drives, I/O modules, grippers, and sensing devices. Its design must provide bounded cycle time, synchronized motion, reliable fault handling, and clear separation between real-time control and higher-level robot intelligence.

The embedded computing platform typically runs Linux with real-time extensions such as PREEMPT_RT on a multicore processor. One or more dedicated Ethernet interfaces are assigned exclusively to the EtherCAT network, while separate interfaces handle ROS 2, fleet communication, diagnostics, and external services. CPU resources, interrupt routing, memory behavior, and network ownership must be planned together because deterministic EtherCAT execution depends on the entire host architecture rather than the protocol stack alone.

A representative EtherCAT topology connects the master to wheel drives, steering actuators, manipulator servo drives, gripper controllers, safety-aware I/O devices, and additional distributed modules in a logical line or branched arrangement. EtherCAT processes frames while they pass through each slave, enabling efficient cyclic exchange across many devices. The resulting architecture allows the mobile base and manipulator to share a synchronized industrial communication domain without requiring independent point-to-point control links for every actuator.

The software architecture should separate the EtherCAT master stack, network configuration, cyclic process-data engine, device abstraction, control interfaces, diagnostics, and application integration. A master library such as SOEM can provide low-level protocol functions, while the surrounding embedded software manages lifecycle, timing, configuration, and fault policy. This separation prevents robot applications from manipulating raw EtherCAT frames and provides stable actuator interfaces even when individual slave devices change.

Startup begins by establishing exclusive ownership of the EtherCAT network interface and discovering the connected slaves. The master identifies each device, checks vendor and product information, configures communication parameters, maps process data, and verifies the expected network topology. Startup should fail safely if required drives are missing, devices appear in unexpected positions, or configuration information differs from the validated machine definition, rather than attempting motion with an uncertain hardware configuration.

Process Data Objects (PDOs) carry cyclic information between the master and slaves. Output PDOs may contain control words, target positions, velocities, torque references, operating modes, and digital outputs, while input PDOs return status words, actual positions, velocities, currents, temperatures, and fault information. PDO layouts should be defined as version-controlled interface contracts because incorrect offsets, sizes, signedness, or scaling can translate directly into incorrect physical actuator commands.

Service Data Objects (SDOs) complement cyclic PDO communication by supporting configuration and parameter access outside the primary real-time data path. SDO operations can configure drive parameters, retrieve device information, or support maintenance functions, but potentially slow mailbox transactions should not interfere with the deterministic cyclic thread. The architecture therefore separates configuration traffic from time-critical process-data exchange and restricts nonessential operations while coordinated motion is active.

The real-time EtherCAT cycle is implemented as a periodic execution loop with a defined period, for example 1 ms for a 1 kHz supervisory servo interface when appropriate for the robot design. During each cycle, the master receives process data, validates network state, updates actuator feedback, executes or exchanges control calculations, writes new commands, and transmits the next frame. Worst-case execution time and jitter must remain comfortably within the selected cycle deadline.

CPU isolation is useful for protecting this periodic loop from unrelated Linux workloads. A dedicated processor core can execute the EtherCAT thread while CPU affinity and IRQ affinity route relevant network interrupts predictably. Memory locking with mlockall prevents page faults after initialization, and real-time scheduling policies give the cyclic thread priority over ordinary applications. Dynamic memory allocation, filesystem access, blocking logging, and unpredictable system calls should be excluded from the critical loop.

Distributed Clocks (DC) provide a key mechanism for synchronizing multiple EtherCAT slaves. Instead of allowing every servo drive to operate from an independent oscillator, distributed clock synchronization establishes a common time reference with tightly controlled phase relationships. This is particularly important for manipulators because coordinated multi-axis motion depends on joints sampling feedback and applying commands at consistent instants. Synchronization quality should therefore be continuously monitored rather than assumed after startup.

The mobile base and manipulator may have different control bandwidths while sharing the same EtherCAT cycle. Wheel velocity or steering commands can be updated according to base-control requirements, while manipulator joints exchange position, velocity, and torque-related data at rates appropriate for servo coordination. A rate-transition layer can connect these actuator domains to higher-level navigation and manipulation software without forcing every algorithm to execute at the EtherCAT network frequency.

Device abstraction prevents higher-level software from depending on vendor-specific register layouts. Each drive adapter can translate standardized robot commands into device-specific PDO representations and convert returned values into consistent engineering units. For example, encoder counts become radians, drive velocity units become radians per second, and current measurements become amperes. This layer can also normalize control modes, fault codes, homing behavior, and enable sequences across heterogeneous servo products.

For manipulator drives using CiA 402-compatible behavior, the embedded software must coordinate the drive state machine carefully. Control words and status words govern transitions through states such as switch-on disabled, ready to switch on, switched on, operation enabled, quick stop, and fault. Motion commands must not be issued simply because network communication exists. Each axis should demonstrate the required operational state before coordinated manipulator motion is permitted.

Command generation must also enforce physical and software limits. Joint position, velocity, acceleration, torque, and following-error limits protect the manipulator from invalid references, while mobile-base commands require equivalent limits for wheel velocity and steering behavior. The EtherCAT layer should reject nonfinite values, impossible ranges, stale commands, and inconsistent operating modes before they reach servo drives. Higher-level software errors should therefore degrade into bounded behavior rather than unrestricted actuator requests.

Communication supervision detects failures that could otherwise propagate rapidly through the robot. The master should monitor working counters, slave states, cycle timing, link status, synchronization error, and command freshness. A mismatch in the expected working counter can indicate that one or more slaves failed to process a frame correctly. Persistent communication anomalies should trigger predefined degradation or stopping behavior instead of allowing the control system to continue with incomplete feedback.

Fault management should distinguish individual-axis faults from failures affecting coordinated motion. A gripper fault may permit the mobile base to remain stationary while diagnostics are performed, whereas loss of a critical arm joint during manipulation may require the complete manipulator to stop. Loss of a wheel drive can require the mobile platform to enter a controlled safe state. Fault policy must therefore reflect mechanical dependencies and system-level hazards rather than treating every EtherCAT error identically.

Safety functions should remain architecturally independent from ordinary EtherCAT motion control where required by the risk assessment. Emergency-stop circuits, Safe Torque Off (STO), safety scanners, protective stops, and safety-rated controllers should retain authority to remove or limit actuator energy even if the EtherCAT master or Linux host fails. The standard EtherCAT master can observe safety status and coordinate application behavior, but normal software communication should not become the sole mechanism protecting people from hazardous motion.

A mobile manipulator introduces an additional coordination challenge because arm movement changes the physical state of the mobile platform. Manipulator extension can shift the center of mass, alter stability margins, enlarge the collision envelope, and change allowable base acceleration. The embedded interface should therefore expose synchronized base and arm states to supervisory control. Motion policies can then restrict base velocity, arm configuration, or simultaneous movement when mechanical stability or operational safety requires it.

Diagnostics should record cycle latency, jitter, missed deadlines, working-counter errors, slave-state transitions, synchronization deviation, drive faults, and communication recovery events. High-frequency data should use bounded buffers rather than synchronous disk writes from the real-time thread. Event-triggered snapshots can preserve process data surrounding a fault, allowing engineers to reconstruct whether the initiating condition originated in a drive, communication network, control algorithm, timing violation, or external safety event.

Recovery behavior must be deterministic. If a slave temporarily leaves its expected operational state, the master may attempt controlled reconfiguration when system policy permits, but automatic recovery must never unexpectedly restore actuator torque. Re-enabling motion should require confirmation of network integrity, valid feedback, appropriate safety state, and compatible application state. Severe or repeated communication failures should transition the robot toward a known safe condition and preserve diagnostic evidence for maintenance.

Testing should combine software simulation, loopback or virtual-slave testing, Hardware-in-the-Loop (HIL), and complete robot validation. Fault injection can deliberately disconnect slaves, delay frames, corrupt configuration, create working-counter mismatches, or force drives into fault states. Timing tests should measure latency distributions and worst-case jitter under CPU, storage, network, and perception workloads, demonstrating that deterministic control remains valid when the mobile manipulator experiences realistic computational stress.

The resulting EtherCAT master is more than an industrial network driver. It forms the deterministic embedded coordination layer between autonomous software and distributed physical actuators, integrating synchronized communication, real-time scheduling, device abstraction, drive state management, fault supervision, and diagnostics. When combined with independent safety mechanisms and carefully defined recovery policies, this architecture enables the mobile base and manipulator to operate as one coordinated robotic system while preserving predictable timing, maintainability, and fault containment.

12.04 Quadruped Joint MCU Firmware Architecture Case

A quadruped robot joint MCU is the lowest embedded control layer that converts coordinated locomotion commands into precise electrical actuation at each leg joint. While the main computer estimates terrain, plans motion, and generates gait targets, the joint controller must execute deterministic servo functions with minimal latency. Its firmware architecture therefore emphasizes high-rate motor control, synchronized sensing, bounded execution time, local protection, robust communication, and predictable transition to safe states.

A typical quadruped contains twelve or more actuated joints distributed across hip, thigh, and knee mechanisms. Each joint may use a brushless permanent-magnet motor, inverter, position encoder, current sensors, temperature sensing, and reduction mechanism. A dedicated MCU may control one actuator or several nearby joints. Distributed controllers reduce wiring complexity and computational load on the main processor while allowing electrical protection and fast servo loops to remain physically close to each motor.

The firmware can be organized into hardware abstraction, peripheral drivers, sensing, motor control, communication, safety supervision, diagnostics, and application state management. Hardware-specific register access belongs inside the Hardware Abstraction Layer (HAL), while control algorithms operate through stable interfaces. This organization makes it possible to change MCU variants, encoder devices, gate drivers, or current-sensing circuits without redesigning the complete joint-control software.

A high-performance ARM Cortex-M MCU can provide advanced timers, synchronized ADCs, DMA, communication peripherals, floating-point processing, watchdogs, and hardware protection resources. PWM timers drive the inverter switching sequence, while ADC conversions are synchronized with PWM timing so phase currents are sampled at electrically meaningful points. DMA transfers repetitive measurements efficiently, allowing the processor to reserve deterministic execution time for current estimation and control calculations.

Joint firmware normally operates through multiple timing domains. The innermost current or torque-control loop may execute at tens of kilohertz, while velocity and position loops operate at lower frequencies. Communication with the robot-level controller may occur around a kilohertz depending on system architecture, whereas diagnostics and thermal monitoring can execute much more slowly. Explicit rate separation prevents maintenance and communication tasks from disturbing the motor-control deadlines.

The interrupt architecture should give the highest priority to time-critical motor-control events. PWM or ADC interrupts trigger current acquisition and control computation, while communication and diagnostic processing execute at lower priorities. Interrupt service routines should avoid blocking operations, filesystem access, dynamic memory allocation, and unpredictable computation. Worst-case execution time must remain below the available control period even when communication traffic and diagnostic activity reach their maximum expected load.

Sensor acquisition begins with rotor position and motor-current measurements. Absolute or incremental encoders provide mechanical position, while current sensors measure phase or inverter current required for torque regulation. Measurements require scaling, offset compensation, calibration, filtering, and validity checking. Position discontinuities, impossible velocity changes, current-sensor saturation, or inconsistent encoder states should be detected before corrupted measurements enter the servo-control calculations.

Field-Oriented Control (FOC) is commonly suitable for high-performance quadruped joints because it enables precise torque production from brushless motors. Rotor electrical angle and phase currents are transformed into rotating reference coordinates, where current components can be regulated independently. Controller outputs are transformed back into voltage commands and converted into PWM duty cycles. The resulting inner loop provides the fast torque response required for dynamic locomotion and disturbance rejection.

Above the current loop, velocity and position controllers translate robot-level joint references into torque-producing commands. The controller may support position, velocity, torque, impedance, or hybrid operating modes depending on locomotion strategy. Impedance control is particularly useful for legged robots because commanded stiffness and damping can regulate how the joint responds to terrain contact. Mode transitions must be explicitly managed to prevent discontinuous torque when locomotion software changes control strategies.

Command interfaces should define position, velocity, torque, stiffness, damping, enable state, and control mode using consistent physical units. Before applying a received command, firmware should check numeric validity, range limits, timestamps or sequence information, and communication freshness. NaN values, excessive torque requests, impossible positions, stale commands, or unsupported operating modes must be rejected locally rather than being transmitted directly to the inverter.

Joint limits provide another layer of protection independent of the higher-level locomotion planner. Firmware can enforce allowable position, velocity, current, torque, temperature, and acceleration boundaries. Soft position limits progressively restrict commands before the mechanical stop is reached, while hard limits trigger stronger protective reactions. These local constraints remain important because a corrupted gait command or software fault on the main computer can otherwise propagate rapidly into physical leg motion.

Communication between joint controllers and the central computer may use CAN-FD, EtherCAT, or another deterministic industrial network. Command packets flow toward the joints while position, velocity, torque, temperature, voltage, operating state, and fault information return to the central controller. The protocol should define scaling, byte order, message identifiers, update rates, sequence behavior, timeout limits, and compatibility versions so every joint interprets commands identically.

Synchronization is critical because locomotion depends on coordinated action across all legs. Joint controllers should share a sufficiently consistent time base or execute commands according to synchronized communication cycles. Without synchronization, small phase differences between joints can distort foot trajectories, contact timing, and force distribution. Timestamped commands, synchronized network cycles, or distributed clock mechanisms can therefore become part of the control architecture for high-performance quadrupeds.

The firmware state machine governs actuator lifecycle behavior. Typical states include boot, initialization, self-test, calibration, disabled, ready, enabled, running, fault, and recovery. Torque output remains inhibited until power conditions, sensor validity, communication status, calibration information, and safety conditions are acceptable. A controller returning from reset should never resume the previous torque command automatically because the mechanical state of the leg may have changed during the interruption.

Quadruped joints experience severe transient loads during foot impact, jumping, slipping, recovery motions, and uneven-terrain traversal. Firmware should continuously supervise overcurrent, bus overvoltage and undervoltage, motor and inverter temperature, encoder failure, excessive velocity, following error, and stalled actuator conditions. Protection thresholds may distinguish warnings, temporary derating, controlled stopping, and immediate power-stage inhibition according to the severity of the detected condition.

Thermal management is especially important because compact joint modules combine motors, reduction mechanisms, electronics, and power stages in limited space. Temperature models can supplement direct sensors to estimate winding or semiconductor heating that is difficult to measure instantaneously. As thermal margins decrease, firmware can reduce allowable continuous torque while preserving short-duration peak capability where safe. This provides graceful performance degradation rather than abrupt thermal shutdown during sustained locomotion.

Fault handling should classify events according to their effect on local and whole-body stability. Some sensor warnings may permit continued operation with reduced capability, while encoder loss or severe inverter faults may require immediate torque removal. Because disabling one leg joint can destabilize the entire robot, the controller should report faults to the central locomotion system with minimal delay. System-level recovery can then coordinate posture stabilization, controlled collapse, or emergency stopping.

A hardware watchdog protects against firmware deadlock, but it should be refreshed only after essential control activities complete successfully. Independent hardware fault inputs from the gate driver or power stage can disable PWM faster than ordinary application software. On reset or severe fault, PWM outputs should enter a predefined inactive condition. Combining MCU supervision with hardware-level shutdown prevents a software failure from leaving uncontrolled switching commands applied to the motor inverter.

Diagnostics should capture information useful for reconstructing difficult locomotion failures. Relevant data include reset cause, fault code, peak current, minimum bus voltage, maximum temperature, encoder anomalies, communication timeouts, and timing overruns. A bounded high-speed event buffer can preserve several control cycles surrounding a critical event. This is valuable when diagnosing intermittent failures that occur only during impacts, high-torque maneuvers, or specific gait transitions.

Nonvolatile memory can store calibration constants, joint identity, hardware revision, firmware version, encoder offsets, protection parameters, and selected lifecycle statistics. Configuration data should include integrity checks and explicit version information so incompatible structures are not silently accepted after firmware changes. Flash writes must be rate-limited because high-frequency diagnostic events can otherwise exhaust endurance long before the mechanical joint reaches its expected service life.

Firmware updates require the same attention to safety as normal motor operation. A bootloader can verify digitally signed images before execution and preserve a recovery image if an update is interrupted. During update mode, motor outputs should remain disabled. Compatibility between joint firmware, communication protocol, and central locomotion software must be controlled because differences in torque scaling, control-mode definitions, or message layouts could create dangerous behavior even when each component operates correctly by itself.

Verification should progress from unit testing and motor simulation to Hardware-in-the-Loop (HIL), actuator dynamometer testing, and complete quadruped experiments. Tests should include sensor faults, communication loss, command saturation, encoder discontinuities, overcurrent events, watchdog resets, thermal derating, and timing overload. Whole-robot testing should then evaluate standing, walking, trotting, impacts, slips, terrain transitions, and emergency conditions while monitoring synchronization and joint-level protection behavior.

The resulting joint MCU firmware is therefore more than a local motor driver. It forms a distributed real-time actuation layer that transforms whole-body locomotion intent into synchronized joint torque while protecting each electromechanical actuator. High-rate FOC, multi-rate servo control, synchronized communication, local command validation, thermal protection, deterministic state management, watchdog supervision, diagnostics, and secure lifecycle mechanisms together provide the foundation for responsive, stable, and fault-aware quadr...