STATERA Library · Series 08 · Volume 05 · Chapter 09 · EN
Source: https://github.com/Statera-Library/08_Vol_05_Robot_Middleware_and_ROS2/blob/main/Chapter_09_ROS2_for_AMR/Chapter_09_ROS2_for_AMR_EN.md

Volume 05 Robot Middleware and ROS2

09. ROS2 for AMR

09.01 AMR ROS2 Software Stack Configuration Overview

An Autonomous Mobile Robot (AMR) built on ROS2 is best organized as a layered software stack in which hardware access, sensing, localization, navigation, motion control, safety, diagnostics, and fleet interaction remain functionally separated while communicating through standardized ROS2 interfaces. This organization allows individual components to evolve independently and establishes a reusable platform for different AMR products.

At the lowest layer, the hardware abstraction and device interface components connect ROS2 to motors, encoders, brakes, batteries, LiDARs, cameras, IMUs, safety devices, and auxiliary I/O. Sensor drivers convert vendor-specific protocols into standard ROS2 messages, while drive interfaces expose velocity, wheel state, and actuator commands. ros2_control can provide a structured boundary between higher-level motion software and physical drivetrain hardware.

The robot model provides the common geometric reference required by the entire AMR stack. URDF or related descriptions define the chassis, wheels, sensors, coordinate frames, and physical relationships among components. tf2 then maintains transformations such as map, odom, base_link, laser, camera, and IMU frames. Correct frame conventions and timestamps are essential because localization, obstacle detection, planning, visualization, and control all depend on consistent spatial information.

The perception layer transforms raw sensor streams into information that can be consumed by localization and navigation. LiDAR scans, depth images, point clouds, wheel odometry, and inertial measurements may be filtered, synchronized, transformed, and fused before reaching higher-level components. ROS2 QoS policies should be selected according to the characteristics of each stream so that high-rate sensor traffic does not unnecessarily delay control or operational messages.

Localization determines the AMR pose relative to its operating environment. During map creation, SLAM software combines motion estimates and environmental observations to construct a persistent representation of the workspace. During normal operation, localization nodes estimate the robot pose against an existing map while odometry supplies continuous local motion information. The resulting map-to-odom-to-base_link relationship becomes a fundamental spatial backbone for autonomous navigation.

Navigation2, commonly referred to as Nav2, forms the principal autonomous navigation framework in a ROS2 AMR configuration. It combines global and local planning, costmaps, behavior execution, recovery mechanisms, controller interfaces, and lifecycle-managed servers. Rather than treating navigation as one monolithic algorithm, Nav2 organizes navigation as cooperating components whose plugins and parameters can be selected according to vehicle kinematics, environment structure, and operational requirements.

Global planning determines a feasible route from the current pose toward a mission goal using map and cost information, while local planning or trajectory control continuously converts that intent into executable motion. Local costmaps incorporate nearby obstacles and updated sensor observations, allowing the robot to react to dynamic conditions. Velocity commands eventually reach the drivetrain interface, closing the software path from mission request through navigation decision to physical AMR movement.

Behavior Trees provide an orchestration mechanism above individual Nav2 functions. A navigation mission can include path computation, path following, replanning, waiting, recovery, obstacle handling, and goal validation without embedding every operational decision inside a single controller. Higher-level AMR applications can extend this concept with mission states such as pickup, transport, delivery, docking, charging, inspection, standby, and fault recovery.

Lifecycle management is particularly important for production AMRs because software components cannot simply be assumed to start successfully at power-on. Sensor drivers, localization, navigation, control, and application nodes may have explicit dependencies and initialization conditions. ROS2 lifecycle nodes allow components to move through controlled configuration, activation, deactivation, cleanup, and shutdown states, enabling deterministic startup sequences and more systematic recovery from runtime failures.

Safety functions should remain architecturally distinct from ordinary autonomous navigation. Navigation software may avoid obstacles and optimize motion, but safety-rated functions can require independent scanners, controllers, emergency-stop circuits, protective fields, or certified communication paths. ROS2 can distribute safety status and coordinate safe operational responses, while the final safety authority should remain consistent with the hardware architecture and applicable functional-safety requirements.

Diagnostics and observability form another cross-cutting layer of the AMR stack. Nodes should expose health information for sensors, localization quality, navigation status, controller state, battery condition, communication quality, CPU and memory utilization, temperature, and software faults. Logging, ros2_diagnostics, tracing, metrics collection, and operational dashboards allow engineers to distinguish algorithmic failures from hardware, timing, networking, or configuration problems.

A production AMR also requires interfaces beyond the autonomous navigation stack. Docking software coordinates localization, alignment, charger communication, and final low-speed motion. Mission-management components translate warehouse or facility tasks into robot behaviors, while fleet interfaces exchange robot state, task status, traffic information, and commands with external management systems. Multi-robot deployments additionally require disciplined namespaces, domain configuration, and communication policies.

DDS provides the distributed communication foundation beneath ROS2 and makes communication configuration part of AMR system architecture rather than merely a networking detail. Reliability, durability, history depth, deadlines, discovery behavior, multicast configuration, and domain isolation influence how sensor, command, status, and fleet information moves through the robot. Appropriate QoS profiles should therefore be defined according to the semantic and timing requirements of each data path.

The complete stack should also separate time-critical control from computationally intensive autonomy. Motor regulation and safety-critical loops may execute in dedicated controllers, MCUs, or real-time environments, while ROS2 handles supervisory control, navigation, perception, mission execution, and system coordination. PREEMPT_RT, executor configuration, memory management, callback-group design, and carefully controlled communication can improve determinism where ROS2 participates in latency-sensitive processing.

Deployment configuration converts these software components into an operational robot product. Launch files, parameter sets, lifecycle orchestration, containers, environment variables, device permissions, network configuration, security policies, and hardware-specific profiles should be version controlled together. CI/CD and OTA mechanisms can then reproduce validated configurations across development robots and production fleets while retaining rollback capability when a new software release produces unexpected behavior.

An AMR ROS2 stack should therefore be understood as an integrated runtime architecture rather than simply a collection of ROS2 packages. Hardware interfaces provide physical connectivity; perception interprets sensors; localization establishes robot pose; Nav2 produces autonomous movement; lifecycle and diagnostics maintain operational integrity; safety constrains behavior; and mission and fleet layers connect individual robots to larger logistics or service processes. This layered organization is consistent with the broader robotics software structure in which middleware, navigation, fleet intelligence, perception, control, and deployment remain coordinated but modular concerns.

09.02 Navigation2 (Nav2) Architecture Deep Dive [w/Code]

Navigation2, commonly called Nav2, is the ROS2 navigation framework that coordinates localization, environmental representation, path planning, trajectory control, behavior execution, and recovery for autonomous mobile robots. Rather than implementing navigation as a single process, Nav2 distributes these responsibilities among lifecycle-managed servers connected through ROS2 topics, services, and actions. This modular structure allows navigation functions to be configured or replaced without redesigning the complete AMR software stack.

The central architectural principle of Nav2 is server-oriented decomposition. Major capabilities such as planning, control, behaviors, waypoint execution, and navigation orchestration operate as independent ROS2 components. Each server exposes well-defined interfaces and typically supports dynamically loadable plugins. Consequently, an AMR developer can select algorithms according to vehicle kinematics, sensor configuration, operating environment, computational resources, and required navigation performance while preserving the surrounding system architecture.

The Behavior Tree Navigator, commonly implemented through the bt_navigator component, coordinates the overall navigation process. A navigation request such as NavigateToPose is translated into a sequence of operations that may compute a path, execute that path, monitor progress, detect failures, invoke recovery behaviors, and retry navigation. Behavior Trees separate mission-level navigation logic from individual planning and control algorithms, making complex navigation workflows easier to modify and inspect.

The Planner Server provides global path-planning functionality. It receives the robot pose, destination, map information, and global costmap context and invokes a configured planner plugin to generate a collision-aware path toward the goal. Different planning algorithms can be selected for different robot geometries and operating conditions. The resulting path represents a geometric navigation intention rather than direct actuator commands and is subsequently consumed by the control stage.

The Controller Server transforms the planned path into executable robot motion. Controller plugins continuously evaluate the robot pose, local environmental conditions, kinematic constraints, and reference path to generate velocity commands. Because this process operates repeatedly while the robot moves, controller performance directly affects path tracking, obstacle response, smoothness, and stability. Controller configuration must therefore reflect the AMR drivetrain, acceleration limits, maximum velocity, footprint, and expected operating environment.

Costmaps provide the spatial representation used by planning and control. The global costmap typically represents a wider operating area and supports route generation, while the local costmap maintains a continuously updated representation around the moving robot. Costmap layers can incorporate static maps, obstacle observations, inflation regions, voxel information, or application-specific data. This layered architecture separates environmental information sources while combining them into a common navigation representation.

Sensor observations enter costmaps through configured ROS2 data sources. LiDAR scans, point clouds, depth-derived obstacles, and other perception results can update occupied or cleared regions around the AMR. Accurate timestamps and tf2 transformations are critical because observations must be transformed into the correct navigation frame before they can influence planning. Sensor latency, update frequency, observation persistence, and clearing behavior consequently become important parameters in practical Nav2 deployments.

The map, odom, and base_link coordinate frames form the principal spatial relationship underlying Nav2. The map frame provides a globally consistent navigation reference, odom represents locally continuous motion, and base_link represents the robot body. Localization or SLAM normally establishes the map-to-odom transform, while wheel odometry or state estimation supports odom-to-base_link. Errors or discontinuities in this transform chain can propagate directly into planning, costmap alignment, and controller behavior.

Localization is therefore closely coupled with Nav2 even though it remains a distinct subsystem. An AMR may use AMCL with a previously generated map, SLAM Toolbox during mapping or localization workflows, or another localization system that provides the required pose and transforms. Nav2 primarily depends on receiving a sufficiently accurate and timely robot pose. This separation allows localization technology to evolve independently while maintaining stable navigation interfaces.

The Behavior Server supplies reusable navigation behaviors that can be invoked when ordinary path execution is insufficient or unsuccessful. Operations such as spinning, backing up, waiting, or other controlled maneuvers can help the robot escape temporary navigation failures. These behaviors are not merely emergency actions; they form part of a structured fault-handling strategy in which the Behavior Tree determines when a behavior should execute and whether navigation should subsequently be retried.

Progress checking and goal checking add explicit execution criteria to the navigation process. A progress checker determines whether the robot is making sufficient movement toward its objective, helping identify situations in which it is physically blocked or unable to follow the requested path. A goal checker determines whether position and orientation tolerances have been satisfied. Separating these criteria from the controller allows completion and failure conditions to be adapted independently for different AMR missions.

Waypoint and route-oriented functions extend navigation beyond a single destination. An AMR can receive sequences of poses representing inspection locations, logistics stations, intermediate route points, or operational checkpoints. Higher-level mission software can combine these navigation functions with actions such as loading, unloading, waiting, scanning, docking, or interacting with equipment. Nav2 therefore serves as the mobility execution layer beneath broader AMR mission and fleet-management systems.

Lifecycle management is deeply integrated into the Nav2 architecture. Core servers can transition through unconfigured, inactive, active, and finalized states, allowing startup to occur only after required parameters, plugins, maps, transforms, and dependencies are available. A lifecycle manager coordinates these transitions and can supervise participating nodes. This mechanism is particularly valuable for production AMRs because navigation should not become active before localization, sensors, control interfaces, and required environmental information are operational.

ROS2 actions are especially suitable for Nav2 because navigation commands are long-running asynchronous operations. Actions allow a client to issue a navigation goal, receive continuous feedback, obtain a final result, or cancel the operation while it is executing. Topics carry continuously changing information such as sensor observations and velocity commands, while services support shorter request-response interactions. Together these communication patterns provide clear boundaries among navigation components and external AMR applications.

Nav2 configuration is largely parameter-driven. Planner and controller plugins, costmap dimensions, robot footprint, obstacle layers, inflation parameters, velocity limits, transform tolerances, update frequencies, progress conditions, and Behavior Tree definitions collectively determine system behavior. Configuration should therefore be treated as part of the robot software baseline rather than as incidental tuning data. Parameter files should be version controlled and validated for each drivetrain, sensor configuration, and deployment environment.

Performance depends on the interaction of the complete navigation pipeline rather than on any single algorithm. Excessive sensor latency may create stale obstacles, inaccurate localization may distort path tracking, inappropriate costmap inflation may prevent passage through valid spaces, and aggressive controller parameters may produce unstable motion. Effective Nav2 engineering consequently requires synchronized evaluation of sensing, transforms, localization, costmaps, planning, control, ROS2 communication, and physical vehicle dynamics.

For production AMRs, navigation must also coexist with independent safety mechanisms. Nav2 can detect obstacles, generate collision-aware paths, regulate motion, and trigger behavioral responses, but ordinary navigation functions should not automatically be treated as safety-rated protection. Emergency stops, certified scanners, protective fields, safety controllers, and drivetrain safety functions may independently override navigation commands. The ROS2 architecture should expose their operational state while preserving the authority of the dedicated safety path.

Within the broader ROS2 AMR architecture, Nav2 occupies the critical layer between spatial intelligence and physical movement. Localization and perception provide knowledge about robot state and surroundings; costmaps transform that knowledge into navigation constraints; planners determine where to move; controllers determine how to move; behaviors handle exceptional conditions; and Behavior Trees coordinate the complete process. This decomposition makes Nav2 a configurable navigation framework capable of supporting both individual AMRs and larger multi-robot operational systems.

09.03 SLAM Toolbox Integration: Map Generation [w/Code]

SLAM Toolbox is a ROS2-native simultaneous localization and mapping framework designed primarily for two-dimensional LiDAR-based robots. Within an AMR software stack, it converts laser observations, odometry, and coordinate transformations into a persistent occupancy-grid map while estimating the robot trajectory. Its integration provides the mapping foundation required by localization, Navigation2, visualization, map management, and later autonomous operation.

The mapping pipeline begins with reliable sensor and motion inputs. A laser scanner normally publishes sensor_msgs/LaserScan data, while wheel odometry or a fused state estimator provides continuous local motion information. tf2 connects the sensor frame to base_link and maintains the relationship between base_link and odom. SLAM Toolbox combines these inputs to estimate successive robot poses and align new laser observations with the evolving representation of the environment.

Coordinate-frame consistency is fundamental to successful map generation. The odom frame provides locally continuous motion but may accumulate drift, whereas the map frame represents the globally corrected reference established by SLAM. SLAM Toolbox estimates the map-to-odom transformation while the robot platform supplies odom-to-base_link. Sensor transforms then connect base_link to laser or other observation frames, creating the complete spatial chain required for scan matching.

During online mapping, incoming laser scans are associated with estimated robot poses and incorporated into a pose graph. Selected poses become graph nodes, while spatial constraints between observations form graph edges. Scan matching estimates relationships among these nodes, and graph optimization adjusts the accumulated trajectory when better constraints become available. This process reduces accumulated odometric error and improves consistency between different portions of the generated map.

Loop closure is particularly important when an AMR returns to a previously observed location. The system attempts to recognize correspondence between current sensor observations and earlier mapped regions and introduces additional constraints into the pose graph. Successful loop closure can correct drift accumulated over a long trajectory. Poor sensor geometry, repetitive environments, moving objects, or inaccurate odometry can make this process more difficult and must therefore be considered during mapping.

SLAM Toolbox supports synchronous and asynchronous mapping modes that represent different processing strategies. Synchronous processing handles observations in sequence and can be useful when deterministic scan handling is important. Asynchronous operation can process incoming data with greater flexibility when sensor rates and available computing resources differ. The appropriate mode should be selected according to AMR speed, LiDAR frequency, processor capacity, map complexity, and required mapping responsiveness.

Map quality depends strongly on the physical robot configuration and data quality rather than solely on the SLAM algorithm. Incorrect LiDAR mounting transforms, wheel slip, poor encoder calibration, vibration, insufficient environmental geometry, or timestamp errors can create duplicated walls, distorted corridors, or inconsistent loops. Before tuning advanced SLAM parameters, engineers should therefore verify sensor calibration, odometry scale, coordinate frames, timestamp consistency, and the mechanical stability of the sensor installation.

Mapping parameters determine how frequently scans are processed and how strongly candidate constraints are accepted. Scan matching thresholds, search dimensions, minimum travel distance, minimum heading change, loop-closure criteria, correlation parameters, and optimization settings influence both computational cost and map consistency. Excessively permissive settings can introduce incorrect constraints, while overly restrictive settings may prevent useful corrections. Parameter tuning should therefore be validated against representative AMR operating environments.

The occupancy-grid representation generated from SLAM can be consumed directly by ROS2 navigation tools and visualized using RViz2. Occupied cells represent structures or obstacles detected by the mapping process, free cells indicate observed traversable regions, and unknown cells identify areas that have not been sufficiently observed. Map resolution determines the spatial granularity of this representation and creates a tradeoff among geometric detail, memory consumption, computational cost, and navigation requirements.

Map generation should be treated as an operational procedure rather than simply driving the robot around an environment. The AMR should cover important corridors, intersections, docking areas, narrow passages, and operational zones while maintaining sufficient overlap between observations. Smooth motion and repeated observation of structurally informative areas generally provide better constraints than abrupt acceleration or unnecessary rotation. Dynamic obstacles should also be minimized when producing a reference map intended for long-term operation.

A major capability of SLAM Toolbox is serialization of the underlying mapping state. Saving only an occupancy-grid image preserves the final map representation, but serialization can retain information associated with the pose graph and mapping session. This enables later continuation or modification of an existing map instead of always beginning from an empty environment. Persistent map workflows are especially useful for industrial AMRs operating in facilities that gradually change over time.

Map saving and map serialization should consequently be distinguished in system design. A conventional map can be exported for use by map_server and localization components, while a serialized SLAM state supports continued mapping or pose-graph-based workflows. Production systems should manage these artifacts with explicit identifiers, versions, creation dates, environment metadata, and robot configuration information so that an outdated or incompatible map is not accidentally deployed.

SLAM Toolbox can also participate in localization workflows after map creation. Instead of continuously constructing a completely new environment representation, the system can use an existing serialized map and estimate the robot pose relative to it. This provides an alternative to localization approaches such as AMCL for some system architectures. The selection should depend on map-management strategy, environmental change, localization behavior, computational resources, and the operational requirements of the AMR.

Integration with Navigation2 requires a clear transition between mapping and autonomous navigation. During mapping, SLAM Toolbox may provide the map and map-to-odom transform while the robot explores or is manually driven. During production navigation, the saved map is loaded and an appropriate localization method provides the robot pose. Nav2 then uses this spatial information to construct costmaps, calculate paths, control motion, and execute higher-level navigation behaviors.

Lifecycle and startup sequencing should prevent navigation components from operating before their required spatial information becomes available. Sensor drivers, odometry, tf2 transforms, SLAM or localization, map services, costmaps, and Nav2 servers have logical dependencies that should be reflected in launch and lifecycle configuration. Automated checks can verify that laser data is arriving, transforms are valid, localization has converged, and the expected map has loaded before autonomous motion is enabled.

Diagnostics should monitor both the input conditions and output quality of the mapping subsystem. Engineers can observe LiDAR frequency, odometry continuity, transform delays, dropped messages, CPU load, scan-matching behavior, pose corrections, and map consistency. RViz2 is valuable for visually comparing laser observations with the generated map and robot trajectory. rosbag2 or MCAP recordings can preserve sensor and transform data for offline reproduction when mapping failures occur in the field.

Multi-session and long-term map management become increasingly important as AMRs move from laboratory demonstrations to production facilities. Warehouses and factories change because racks, machines, walls, doors, and operational zones may be modified. A robust architecture should distinguish temporary obstacles from structural changes and provide controlled procedures for remapping, updating, validating, approving, and deploying maps without unintentionally corrupting a known-good navigation reference.

Within the complete ROS2 AMR stack, SLAM Toolbox connects physical sensing with persistent spatial knowledge. LiDAR and odometry describe immediate observations and motion; tf2 establishes their geometric relationships; scan matching and pose-graph optimization construct a consistent trajectory; occupancy mapping converts that trajectory into a navigation representation; and map persistence enables later localization and Nav2 operation. This integration transforms raw robot movement into a reusable spatial foundation for autonomous AMR deployment.

09.04 AMR Sensor Driver ROS2 Package Config [w/Code]

An AMR sensor-driver layer provides the software boundary between physical sensing devices and the ROS2 autonomy stack. Its primary responsibility is to convert vendor-specific interfaces, protocols, timestamps, coordinate conventions, and measurement formats into stable ROS2 interfaces. LiDARs, cameras, depth sensors, IMUs, wheel encoders, ultrasonic sensors, and other devices can therefore be consumed consistently by localization, perception, mapping, navigation, diagnostics, and safety-related supervisory software.

A production sensor package should separate hardware communication from ROS2-facing data publication. The hardware layer manages Ethernet, CAN, USB, serial, or other device-specific transport mechanisms, while the ROS2 node converts received measurements into standardized messages. This separation reduces dependency on individual vendors and makes it easier to replace a sensor without modifying every downstream AMR component that consumes its data.

ROS2 package organization should clearly separate source code, launch configuration, parameters, calibration information, and device-specific resources. A sensor package may contain the driver node, reusable communication libraries, launch files, YAML parameter files, diagnostic configuration, and supporting scripts. Package dependencies should explicitly describe required ROS2 interfaces and external libraries so that builds remain reproducible across development computers, robot computers, containers, and CI/CD environments.

Standard ROS2 message types should be preferred whenever they accurately represent the sensor output. A two-dimensional LiDAR commonly publishes sensor_msgs/LaserScan, a three-dimensional LiDAR may use sensor_msgs/PointCloud2, cameras publish sensor_msgs/Image and CameraInfo, and IMUs normally use sensor_msgs/Imu. Wheel encoder information may contribute to nav_msgs/Odometry or joint-state interfaces depending on the drivetrain and state-estimation architecture.

Topic naming should follow a predictable robot-wide convention. Names such as scan, camera/image_raw, camera/camera_info, imu/data, points, and odom allow downstream components to be configured consistently, while namespaces distinguish robots or multiple instances of similar sensors. Remapping should be used when external packages expect different topic names, avoiding unnecessary modifications to driver source code and preserving portability across AMR configurations.

Coordinate-frame configuration is equally important because sensor measurements become useful only when their physical relationship to the robot is known. Each device should have a clearly defined frame such as laser_frame, camera_link, imu_link, or lidar_link connected to base_link through tf2. Fixed mounting relationships can be published as static transforms, while dynamic transforms should originate from the component responsible for estimating the corresponding physical motion.

Sensor calibration parameters should remain separate from ordinary application logic. Camera intrinsics, LiDAR mounting positions, IMU orientation offsets, encoder scale factors, and other calibration values describe the actual physical robot and may differ between individual units. Treating these values as managed configuration data enables per-robot calibration while keeping the same driver software package reusable across a production fleet.

Timestamp integrity is critical for AMRs because localization and sensor fusion combine measurements originating from different devices. Ideally, a driver should preserve a hardware-generated acquisition timestamp when the sensor provides one instead of assigning a timestamp only after data reaches the ROS2 process. Clock synchronization, communication delay, buffering, and timestamp provenance should therefore be considered explicitly when configuring sensors for tightly synchronized perception and localization pipelines.

Quality of Service settings determine how sensor messages behave under varying computational and network conditions. High-rate measurements often favor low-latency delivery and may tolerate occasional sample loss, whereas some state or configuration information may require reliable transmission. Reliability, durability, history depth, queue size, and deadline settings should reflect the semantics of each sensor stream rather than applying one identical QoS profile to every device.

LiDAR configuration typically includes communication addresses, scan frequency, angular limits, range limits, frame identifiers, filtering options, and output topic names. For an AMR using LiDAR for SLAM and obstacle detection, the driver must provide stable scan timing and valid geometric information. Downstream SLAM Toolbox and Nav2 components depend on the correspondence among LaserScan data, odometry, and tf2, so driver-level timing or frame errors can propagate directly into mapping and navigation behavior.

Camera and depth-sensor drivers introduce additional bandwidth and synchronization requirements. Image resolution, pixel format, frame rate, compression, exposure, depth alignment, and camera calibration influence both computational load and perception quality. When RGB and depth streams are combined, their timestamps and optical frames must be correctly related. High-resolution data should be published only when downstream perception actually requires it, particularly on resource-constrained edge computers.

IMU integration requires careful treatment of coordinate orientation, units, covariance, bias, and measurement validity. Angular velocity and linear acceleration may feed robot_localization or another state estimator together with wheel odometry and other motion measurements. Incorrect axis conventions or covariance values can degrade the fused pose even when the raw measurements appear reasonable. Driver validation should therefore include stationary tests, controlled motion tests, and comparison with expected robot-frame behavior.

Wheel encoder and drivetrain sensing provide another essential input to AMR state estimation. Encoder counts must be converted according to wheel radius, gear ratio, encoder resolution, and drivetrain geometry before reliable odometry can be produced. Differential-drive, omnidirectional, and steering-based platforms require different kinematic interpretations. When ros2_control is used, hardware interfaces and controllers can provide a standardized path between encoder feedback, joint states, odometry generation, and commanded motion.

Launch files integrate individual sensor packages into a complete AMR configuration. A top-level robot launch process can start multiple drivers, load parameter files, establish static transforms, configure namespaces, and activate supporting filters or state estimators. Hardware variants should preferably be represented through launch arguments and configuration profiles instead of duplicated source trees, allowing one ROS2 software baseline to support several sensor combinations or robot models.

Lifecycle management can improve sensor startup and recovery behavior. A lifecycle-aware driver may configure hardware resources before activation, begin publication only after successful initialization, stop acquisition during deactivation, and release resources during cleanup. Higher-level orchestration can then ensure that localization and navigation are activated only after required sensors are healthy. Failed devices can also be restarted in a controlled manner without unnecessarily restarting the complete AMR software stack.

Diagnostics should expose more than whether a driver process is running. Useful health information includes message frequency, communication errors, dropped packets, sensor temperature, voltage, timestamp delay, invalid measurements, reconnect attempts, and device status codes. These diagnostics can be aggregated through ROS2 monitoring infrastructure so operators can distinguish a navigation problem from a degraded sensor, network interruption, calibration issue, or driver malfunction.

Driver robustness should include predictable behavior during disconnection and recovery. Ethernet cables can fail, USB devices can reset, serial links can become corrupted, and sensors may temporarily stop transmitting. A production driver should detect these conditions, report them through diagnostics, avoid publishing misleading stale data, and follow an explicit reconnection policy. Recovery behavior must also coordinate with lifecycle, navigation, and safety supervision when the missing sensor is operationally critical.

Sensor configuration should ultimately be validated as an integrated pipeline rather than as isolated device functionality. Engineers should verify topic rates, timestamps, QoS compatibility, tf2 relationships, calibration, CPU usage, network bandwidth, and downstream behavior in SLAM Toolbox, localization, perception, and Nav2. ros2 topic tools, tf2 utilities, RViz2, diagnostics, rosbag2, and tracing provide complementary mechanisms for detecting integration problems before deployment.

Within the overall AMR architecture, ROS2 sensor-driver packages transform heterogeneous physical devices into a coherent sensing infrastructure. Standard messages establish semantic compatibility, tf2 establishes geometric consistency, timestamps establish temporal consistency, QoS controls communication behavior, lifecycle management governs operational state, and diagnostics expose health. Together these mechanisms create a stable sensor boundary upon which mapping, localization, perception, navigation, and higher-level autonomous behavior can reliably operate.

09.05 ros2.control-Based AMR Drive Interface [w/Code]

ros2_control provides a standardized control framework for connecting ROS2 autonomy software to the physical drivetrain of an Autonomous Mobile Robot (AMR). Instead of allowing navigation components to communicate directly with motor drivers, ros2_control introduces hardware interfaces, controllers, and a controller manager between high-level motion commands and actuators. This separation improves portability, testability, hardware replacement, and integration across different AMR platforms.

The central component of the architecture is the Controller Manager, which coordinates hardware resources and controller execution. It loads configured hardware components, activates appropriate controllers, manages their lifecycle, and executes the periodic read-update-write control cycle. From the perspective of higher-level ROS2 software, the Controller Manager creates a consistent runtime environment regardless of whether the physical drivetrain communicates through CAN, EtherCAT, Ethernet, serial communication, or another industrial interface.

The hardware interface represents the boundary between ros2_control and the physical drive system. A custom AMR hardware plugin typically initializes motor controllers, exposes command and state interfaces, reads encoder or drive feedback, and writes requested actuator commands. Vendor-specific communication is therefore isolated inside the hardware implementation instead of being propagated into navigation or application software. Replacing a motor controller can consequently require changes mainly within this interface layer.

State interfaces expose measured drivetrain information to the control framework. Typical wheel-based AMRs provide wheel position and velocity derived from encoders, although additional state information such as steering angle or actuator status may also be available. Command interfaces represent quantities that controllers are permitted to request, such as wheel velocity, steering position, or actuator effort. Clearly defining these interfaces establishes an explicit software contract between controllers and hardware.

For a differential-drive AMR, the differential drive controller converts robot-level linear and angular velocity commands into individual left- and right-wheel commands. Wheel separation, wheel radius, velocity limits, acceleration constraints, and odometry parameters determine this conversion. Encoder feedback is then used to estimate vehicle motion and publish odometry-related information, creating a structured connection between commanded chassis motion, physical wheel movement, and the ROS2 navigation stack.

Other AMR drivetrain configurations require different controller strategies. An omnidirectional platform may independently control several wheels, while an Ackermann or steering-based vehicle must coordinate steering angle and wheel velocity according to vehicle geometry. ros2_control does not require all mobile robots to share one kinematic model; instead, its hardware and controller abstractions allow appropriate control implementations to be selected while maintaining a common system-management architecture.

The command path normally begins with an autonomy component such as Navigation2. Nav2 generates a velocity command representing desired chassis motion, and the configured mobile-base controller converts this command into actuator-level references. The Controller Manager then executes the controller and passes commands through the hardware interface to the motor drives. This creates a clear sequence from navigation intent through kinematic conversion and hardware abstraction to physical motion.

The feedback path operates in the opposite direction. Encoders and motor drives report measured wheel states through the hardware interface, which exposes them to ros2_control. Controllers and state broadcasters can publish joint states, odometry, or related information for other ROS2 components. Localization and state-estimation software can subsequently combine this motion estimate with IMU, LiDAR, GNSS, or other sensor measurements to obtain a more robust estimate of the AMR state.

URDF-based robot descriptions can define the ros2_control hardware structure together with joints and interfaces. Each controlled joint identifies the state and command interfaces supported by the physical system, while plugin definitions associate the robot model with the corresponding hardware implementation. This approach connects the mechanical representation of the AMR to its runtime control architecture and helps maintain consistency among simulation, visualization, control configuration, and actual hardware deployment.

Controller parameters are generally maintained separately from application source code. YAML configuration can specify controller types, wheel joint names, wheel geometry, command timeout, publication rates, velocity limits, acceleration limits, covariance values, and other runtime settings. Separating these values allows the same software implementation to support different AMR dimensions or drivetrain variants while preserving configuration history through version control and deployment management.

Command timeout handling is essential because an AMR must not continue indefinitely using an outdated velocity request. If commands stop arriving because navigation fails, a process crashes, or communication is interrupted, the drive controller should transition toward a defined stopped condition according to its configuration. This mechanism provides an important operational safeguard, although it should not be confused with an independently engineered functional-safety stop or emergency-stop function.

Real-time behavior becomes important around the ros2_control update loop. The sequence of reading hardware state, updating controllers, and writing actuator commands should execute with sufficiently stable timing for the drivetrain dynamics. Excessive scheduling jitter, memory allocation, blocking communication, or slow callbacks can degrade motion quality. PREEMPT_RT, thread priorities, CPU affinity, pre-allocation, and carefully designed hardware communication may therefore be applied when stronger timing determinism is required.

The update frequency should be selected according to drivetrain response, motor-controller behavior, encoder resolution, communication latency, and the dynamic requirements of the AMR. Running the loop unnecessarily fast increases CPU and communication load, whereas an excessively slow loop reduces responsiveness and can degrade trajectory tracking. Performance evaluation should therefore measure actual loop period, jitter, command latency, feedback age, and physical motion rather than relying only on a configured nominal frequency.

Lifecycle and startup sequencing are also important for a production drive interface. Hardware should be initialized and verified before motion controllers become active, and controllers should not accept operational commands until required interfaces are available. During shutdown or fault recovery, command generation should be disabled before hardware resources are released. Coordinating ros2_control with the broader ROS2 lifecycle architecture helps produce deterministic power-on, restart, maintenance, and power-off behavior.

Diagnostics should expose the health of both software and drivetrain hardware. Useful information includes controller state, update frequency, command age, encoder validity, communication errors, motor-driver faults, temperatures, currents, voltages, and emergency conditions reported by the drive system. Monitoring these values allows operators to distinguish navigation failures from mechanical problems, communication faults, controller misconfiguration, or degraded actuator performance.

Safety architecture must remain distinct from ordinary ros2_control motion control. ros2_control can stop publishing motion commands or command zero velocity when a fault occurs, but safety-rated emergency stopping may require independent safety controllers, safe torque off, safety scanners, contactors, or certified fieldbus functions. The normal ROS2 control path can exchange status with these systems, but software motion control should not unintentionally become the sole authority for hazardous-motion prevention.

Simulation can use the same control-oriented architecture before physical hardware is available. A simulated hardware component can expose equivalent state and command interfaces while a simulator models wheel motion and robot dynamics. Controllers and higher-level Nav2 software can therefore operate through interfaces similar to those used on the real AMR. Maintaining this interface consistency reduces differences among software-in-the-loop, simulation, hardware-in-the-loop, and physical-robot testing.

Integration testing should verify the complete command and feedback chain rather than testing only individual controllers. Tests should confirm velocity-command reception, wheel-command conversion, encoder feedback, odometry direction, coordinate conventions, timeout behavior, controller activation, communication-loss handling, and recovery. Low-speed tests should precede full-performance operation so that incorrect wheel signs, geometry parameters, scal...