Skip to main content

Mini-Project: Build & Run a ROS 2 Control Pipeline

In this mini-project, we'll integrate all concepts from Module 1 to build a complete ROS 2 control pipeline for a humanoid robot. This project demonstrates how the ROS 2 architecture, Python agents, URDF modeling, and launch configuration work together to create a functional Physical AI system.

Project Overview​

We'll create a control pipeline for a simplified humanoid robot that can:

  1. Receive high-level navigation goals
  2. Plan paths avoiding obstacles
  3. Execute locomotion using joint control
  4. Adapt behavior based on sensor feedback

Learning Objectives​

  • Integrate ROS 2 concepts into a cohesive system
  • Implement robot control using rclpy
  • Configure a complete robot system with launch files
  • Design parameterized controllers for humanoid robots

System Architecture​

Our pipeline will consist of:

High-Level Planner → Path Planner → Controller → Robot Hardware/Simulation

Components​

  1. Goal Publisher: Sends navigation goals
  2. Path Planner: Computes collision-free paths
  3. Controller: Converts paths to joint commands
  4. Robot Interface: Communicates with hardware/simulation

Implementation Steps​

Step 1: Create the Robot Package Structure​

First, create the package structure:

simple_humanoid_control/
├── CMakeLists.txt
├── package.xml
├── launch/
│ └── control_pipeline.launch.py
├── config/
│ └── humanoid_params.yaml
├── urdf/
│ └── simple_humanoid.urdf
├── scripts/
│ └── goal_publisher.py
└── simple_humanoid_control/
├── __init__.py
├── path_planner.py
├── controller.py
└── robot_interface.py

Step 2: Define the Robot URDF​

Create a simplified humanoid URDF (urdf/simple_humanoid.urdf):

<?xml version="1.0"?>
<robot name="simple_humanoid">
<!-- Base link - pelvis -->
<link name="base_link">
<visual>
<geometry>
<box size="0.2 0.2 0.1"/>
</geometry>
</visual>
<collision>
<geometry>
<box size="0.2 0.2 0.1"/>
</geometry>
</collision>
<inertial>
<mass value="10.0"/>
<inertia ixx="0.1" ixy="0.0" ixz="0.0" iyy="0.1" iyz="0.0" izz="0.1"/>
</inertial>
</link>

<!-- Torso -->
<joint name="torso_joint" type="fixed">
<parent link="base_link"/>
<child link="torso"/>
<origin xyz="0.0 0.0 0.15" rpy="0 0 0"/>
</joint>

<link name="torso">
<visual>
<geometry>
<box size="0.3 0.2 0.4"/>
</geometry>
</visual>
<collision>
<geometry>
<box size="0.3 0.2 0.4"/>
</geometry>
</collision>
<inertial>
<mass value="15.0"/>
<inertia ixx="0.2" ixy="0.0" ixz="0.0" iyy="0.2" iyz="0.0" izz="0.2"/>
</inertial>
</link>

<!-- Head -->
<joint name="neck_joint" type="revolute">
<parent link="torso"/>
<child link="head"/>
<origin xyz="0.0 0.0 0.3" rpy="0 0 0"/>
<axis xyz="0 1 0"/>
<limit lower="-0.5" upper="0.5" effort="5.0" velocity="1.0"/>
</joint>

<link name="head">
<visual>
<geometry>
<sphere radius="0.1"/>
</geometry>
</visual>
<collision>
<geometry>
<sphere radius="0.1"/>
</geometry>
</collision>
<inertial>
<mass value="2.0"/>
<inertia ixx="0.01" ixy="0.0" ixz="0.0" iyy="0.01" iyz="0.0" izz="0.01"/>
</inertial>
</link>

<!-- Left leg -->
<joint name="left_hip_joint" type="revolute">
<parent link="base_link"/>
<child link="left_thigh"/>
<origin xyz="0.05 0.0 -0.05" rpy="0 0 0"/>
<axis xyz="0 1 0"/>
<limit lower="-0.78" upper="0.78" effort="50.0" velocity="1.0"/>
</joint>

<link name="left_thigh">
<visual>
<geometry>
<cylinder length="0.4" radius="0.05"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</visual>
<collision>
<geometry>
<cylinder length="0.4" radius="0.05"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</collision>
<inertial>
<mass value="5.0"/>
<inertia ixx="0.05" ixy="0.0" ixz="0.0" iyy="0.05" iyz="0.0" izz="0.05"/>
</inertial>
</link>

<joint name="left_knee_joint" type="revolute">
<parent link="left_thigh"/>
<child link="left_shin"/>
<origin xyz="0 0 -0.4" rpy="0 0 0"/>
<axis xyz="0 1 0"/>
<limit lower="0" upper="1.57" effort="40.0" velocity="1.0"/>
</joint>

<link name="left_shin">
<visual>
<geometry>
<cylinder length="0.4" radius="0.04"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</visual>
<collision>
<geometry>
<cylinder length="0.4" radius="0.04"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</collision>
<inertial>
<mass value="3.0"/>
<inertia ixx="0.03" ixy="0.0" ixz="0.0" iyy="0.03" iyz="0.0" izz="0.03"/>
</inertial>
</link>

<!-- Right leg (similar to left, mirrored) -->
<joint name="right_hip_joint" type="revolute">
<parent link="base_link"/>
<child link="right_thigh"/>
<origin xyz="-0.05 0.0 -0.05" rpy="0 0 0"/>
<axis xyz="0 1 0"/>
<limit lower="-0.78" upper="0.78" effort="50.0" velocity="1.0"/>
</joint>

<link name="right_thigh">
<visual>
<geometry>
<cylinder length="0.4" radius="0.05"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</visual>
<collision>
<geometry>
<cylinder length="0.4" radius="0.05"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</collision>
<inertial>
<mass value="5.0"/>
<inertia ixx="0.05" ixy="0.0" ixz="0.0" iyy="0.05" iyz="0.0" izz="0.05"/>
</inertial>
</link>

<joint name="right_knee_joint" type="revolute">
<parent link="right_thigh"/>
<child link="right_shin"/>
<origin xyz="0 0 -0.4" rpy="0 0 0"/>
<axis xyz="0 1 0"/>
<limit lower="0" upper="1.57" effort="40.0" velocity="1.0"/>
</joint>

<link name="right_shin">
<visual>
<geometry>
<cylinder length="0.4" radius="0.04"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</visual>
<collision>
<geometry>
<cylinder length="0.4" radius="0.04"/>
</geometry>
<origin xyz="0 0 -0.2" rpy="1.57 0 0"/>
</collision>
<inertial>
<mass value="3.0"/>
<inertia ixx="0.03" ixy="0.0" ixz="0.0" iyy="0.03" iyz="0.0" izz="0.03"/>
</inertial>
</link>
</robot>

Step 3: Create Parameter Configuration​

Create config/humanoid_params.yaml:

# Global parameters
/**:
ros__parameters:
# Robot physical parameters
robot_name: "simple_humanoid"
control_frequency: 50.0
simulation_mode: false
joint_limits:
hip_min: -0.78
hip_max: 0.78
knee_min: 0.0
knee_max: 1.57

# Controller parameters
controller:
kp_linear: 1.0
kp_angular: 1.0
max_linear_speed: 0.3
max_angular_speed: 0.5
safety_distance: 0.5

# Path planning parameters
path_planner:
resolution: 0.1
inflation_radius: 0.3
max_iterations: 1000

# Locomotion parameters
locomotion:
step_height: 0.05
step_length: 0.2
step_duration: 1.0
walk_pattern: "bipedal"

Step 4: Implement the Path Planner​

Create simple_humanoid_control/path_planner.py:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped, Point
from nav_msgs.msg import Path
from sensor_msgs.msg import LaserScan
from builtin_interfaces.msg import Duration
import numpy as np
from scipy.spatial import distance

class SimplePathPlanner(Node):
def __init__(self):
super().__init__('simple_path_planner')

# Declare parameters
self.declare_parameter('path_planner.resolution', 0.1)
self.declare_parameter('path_planner.inflation_radius', 0.3)
self.declare_parameter('path_planner.max_iterations', 1000)

# Get parameters
self.resolution = self.get_parameter('path_planner.resolution').value
self.inflation_radius = self.get_parameter('path_planner.inflation_radius').value
self.max_iterations = self.get_parameter('path_planner.max_iterations').value

# Subscribers
self.goal_sub = self.create_subscription(
PoseStamped,
'goal_pose',
self.goal_callback,
10
)

self.scan_sub = self.create_subscription(
LaserScan,
'scan',
self.scan_callback,
10
)

# Publishers
self.path_pub = self.create_publisher(Path, 'path', 10)
self.cmd_pub = self.create_publisher(PoseStamped, 'next_waypoint', 10)

# Internal state
self.current_goal = None
self.current_scan = None
self.obstacles = []

# Timer for path planning
self.plan_timer = self.create_timer(1.0, self.plan_path)

self.get_logger().info('Simple Path Planner initialized')

def goal_callback(self, msg):
"""Handle new goal pose"""
self.current_goal = msg
self.get_logger().info(f'Received new goal: ({msg.pose.position.x}, {msg.pose.position.y})')
self.plan_path()

def scan_callback(self, msg):
"""Process laser scan to detect obstacles"""
self.current_scan = msg
self.obstacles = self.extract_obstacles_from_scan(msg)

def extract_obstacles_from_scan(self, scan_msg):
"""Extract obstacle positions from laser scan"""
obstacles = []
angle = scan_msg.angle_min

for range_val in scan_msg.ranges:
if not np.isnan(range_val) and range_val < scan_msg.range_max and range_val > scan_msg.range_min:
# Convert to Cartesian coordinates
x = range_val * np.cos(angle)
y = range_val * np.sin(angle)
obstacles.append((x, y))
angle += scan_msg.angle_increment

return obstacles

def plan_path(self):
"""Simple path planning using vector field algorithm"""
if self.current_goal is None or self.current_scan is None:
return

# Get current position (for this example, assume it's the origin)
current_pos = np.array([0.0, 0.0])
goal_pos = np.array([self.current_goal.pose.position.x, self.current_goal.pose.position.y])

# If close to goal, no need for path planning
if np.linalg.norm(goal_pos - current_pos) < 0.1:
self.publish_direct_path(current_pos, goal_pos)
return

# Simple path planning algorithm (vector field with obstacle avoidance)
path_points = self.generate_path_with_obstacle_avoidance(current_pos, goal_pos)

# Publish the path
self.publish_path(path_points)

def generate_path_with_obstacle_avoidance(self, start, goal):
"""Generate path while avoiding obstacles"""
path = [start]
current = start.copy()

for i in range(self.max_iterations):
# Calculate direction to goal
direction_to_goal = goal - current
distance_to_goal = np.linalg.norm(direction_to_goal)

if distance_to_goal < self.resolution:
# Reached goal
path.append(goal)
break

# Normalize and scale to resolution
direction_to_goal = direction_to_goal / distance_to_goal * self.resolution

# Check for obstacles in the path
next_point = current + direction_to_goal

# Simple obstacle avoidance: move around obstacles
for obs_x, obs_y in self.obstacles:
obstacle_pos = np.array([obs_x, obs_y])
if np.linalg.norm(obstacle_pos - next_point) < self.inflation_radius:
# Adjust path to go around obstacle
# For simplicity, move perpendicular to the goal direction
perpendicular = np.array([-direction_to_goal[1], direction_to_goal[0]])
next_point = current + perpendicular * self.resolution * 0.5

path.append(next_point)
current = next_point

return path

def publish_path(self, path_points):
"""Publish the planned path"""
path_msg = Path()
path_msg.header.stamp = self.get_clock().now().to_msg()
path_msg.header.frame_id = 'map'

for i, point in enumerate(path_points):
pose_stamped = PoseStamped()
pose_stamped.header.stamp = self.get_clock().now().to_msg()
pose_stamped.header.frame_id = 'map'
pose_stamped.pose.position.x = float(point[0])
pose_stamped.pose.position.y = float(point[1])
pose_stamped.pose.position.z = 0.0
pose_stamped.pose.orientation.w = 1.0 # No rotation

path_msg.poses.append(pose_stamped)

self.path_pub.publish(path_msg)
self.get_logger().info(f'Published path with {len(path_points)} waypoints')

def publish_direct_path(self, start, goal):
"""Publish a direct path when obstacles are not a concern"""
path_msg = Path()
path_msg.header.stamp = self.get_clock().now().to_msg()
path_msg.header.frame_id = 'map'

# Start point
start_pose = PoseStamped()
start_pose.header.stamp = self.get_clock().now().to_msg()
start_pose.header.frame_id = 'map'
start_pose.pose.position.x = float(start[0])
start_pose.pose.position.y = float(start[1])
start_pose.pose.position.z = 0.0
start_pose.pose.orientation.w = 1.0
path_msg.poses.append(start_pose)

# Goal point
goal_pose = PoseStamped()
goal_pose.header.stamp = self.get_clock().now().to_msg()
goal_pose.header.frame_id = 'map'
goal_pose.pose.position.x = float(goal[0])
goal_pose.pose.position.y = float(goal[1])
goal_pose.pose.position.z = 0.0
goal_pose.pose.orientation.w = 1.0
path_msg.poses.append(goal_pose)

self.path_pub.publish(path_msg)
self.get_logger().info('Published direct path to goal')

Step 5: Implement the Controller​

Create simple_humanoid_control/controller.py:

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped, Twist
from sensor_msgs.msg import JointState
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from builtin_interfaces.msg import Duration
import numpy as np
from enum import Enum

class LocomotionState(Enum):
IDLE = 1
WALKING = 2
TURNING = 3
ADJUSTING = 4

class HumanoidController(Node):
def __init__(self):
super().__init__('humanoid_controller')

# Declare parameters
self.declare_parameter('controller.kp_linear', 1.0)
self.declare_parameter('controller.kp_angular', 1.0)
self.declare_parameter('controller.max_linear_speed', 0.3)
self.declare_parameter('controller.max_angular_speed', 0.5)
self.declare_parameter('locomotion.step_height', 0.05)
self.declare_parameter('locomotion.step_length', 0.2)
self.declare_parameter('locomotion.step_duration', 1.0)

# Get parameters
self.kp_linear = self.get_parameter('controller.kp_linear').value
self.kp_angular = self.get_parameter('controller.kp_angular').value
self.max_linear = self.get_parameter('controller.max_linear_speed').value
self.max_angular = self.get_parameter('controller.max_angular_speed').value
self.step_height = self.get_parameter('locomotion.step_height').value
self.step_length = self.get_parameter('locomotion.step_length').value
self.step_duration = self.get_parameter('locomotion.step_duration').value

# Subscribers
self.path_sub = self.create_subscription(
PoseStamped,
'next_waypoint',
self.waypoint_callback,
10
)

self.odom_sub = self.create_subscription(
PoseStamped,
'robot_pose',
self.odom_callback,
10
)

# Publishers
self.joint_cmd_pub = self.create_publisher(
JointTrajectory,
'joint_trajectory',
10
)

self.cmd_vel_pub = self.create_publisher(Twist, 'cmd_vel', 10)

# Internal state
self.current_waypoint = None
self.current_pose = None
self.locomotion_state = LocomotionState.IDLE
self.joint_names = [
'left_hip_joint', 'left_knee_joint',
'right_hip_joint', 'right_knee_joint',
'neck_joint'
]

# Timer for control loop
self.control_timer = self.create_timer(0.02, self.control_loop) # 50 Hz

self.get_logger().info('Humanoid Controller initialized')

def waypoint_callback(self, msg):
"""Receive next waypoint from path planner"""
self.current_waypoint = msg
if self.locomotion_state == LocomotionState.IDLE:
self.locomotion_state = LocomotionState.WALKING

def odom_callback(self, msg):
"""Receive current robot pose"""
self.current_pose = msg

def control_loop(self):
"""Main control loop"""
if self.current_waypoint is None or self.current_pose is None:
# If no goal or pose, send zero commands
self.send_zero_command()
return

# Calculate control commands
cmd = self.calculate_control_command()

# Generate joint commands for walking
joint_cmd = self.generate_locomotion_commands(cmd)

# Publish commands
self.joint_cmd_pub.publish(joint_cmd)

# Also publish velocity commands (for simulation compatibility)
self.cmd_vel_pub.publish(cmd)

# Update locomotion state based on progress
self.update_locomotion_state()

def calculate_control_command(self):
"""Calculate velocity commands to reach the waypoint"""
if self.current_waypoint is None or self.current_pose is None:
cmd = Twist()
cmd.linear.x = 0.0
cmd.angular.z = 0.0
return cmd

# Calculate distance to waypoint
dx = self.current_waypoint.pose.position.x - self.current_pose.pose.position.x
dy = self.current_waypoint.pose.position.y - self.current_pose.pose.position.y
distance = np.sqrt(dx**2 + dy**2)

# Calculate desired angle
desired_angle = np.arctan2(dy, dx)

# Simple proportional controller
linear_vel = min(self.max_linear, self.kp_linear * distance)
angular_vel = self.kp_angular * desired_angle

# Limit angular velocity
angular_vel = max(-self.max_angular, min(self.max_angular, angular_vel))

cmd = Twist()
cmd.linear.x = linear_vel
cmd.angular.z = angular_vel

return cmd

def generate_locomotion_commands(self, cmd_vel):
"""Generate joint trajectory commands for bipedal locomotion"""
traj_msg = JointTrajectory()
traj_msg.header.stamp = self.get_clock().now().to_msg()
traj_msg.header.frame_id = 'base_link'
traj_msg.joint_names = self.joint_names

# Create trajectory point
point = JointTrajectoryPoint()

# For this example, we'll use a simple walking pattern
# In a real implementation, this would involve complex inverse kinematics

if self.locomotion_state == LocomotionState.WALKING:
# Generate walking pattern
t = self.get_clock().now().nanoseconds / 1e9 # Time in seconds

# Simple walking gait (in reality, this would be much more complex)
left_hip_angle = 0.2 * np.sin(2 * np.pi * t / self.step_duration)
left_knee_angle = 0.1 * np.cos(2 * np.pi * t / self.step_duration)
right_hip_angle = -0.2 * np.sin(2 * np.pi * t / self.step_duration)
right_knee_angle = -0.1 * np.cos(2 * np.pi * t / self.step_duration)

# Head orientation based on direction of movement
head_angle = cmd_vel.angular.z * 0.5

point.positions = [
left_hip_angle, # left_hip_joint
left_knee_angle, # left_knee_joint
right_hip_angle, # right_hip_joint
right_knee_angle, # right_knee_joint
head_angle # neck_joint
]

else:
# Default standing position
point.positions = [0.0, 0.0, 0.0, 0.0, 0.0]

# Set velocities to 0 for now (in reality, would calculate proper velocities)
point.velocities = [0.0, 0.0, 0.0, 0.0, 0.0]

# Set acceleration to 0
point.accelerations = [0.0, 0.0, 0.0, 0.0, 0.0]

# Set effort to 0
point.effort = [0.0, 0.0, 0.0, 0.0, 0.0]

# Set time from start
point.time_from_start = Duration(sec=int(self.step_duration), nanosec=0)

traj_msg.points.append(point)

return traj_msg

def update_locomotion_state(self):
"""Update locomotion state based on progress toward goal"""
if self.current_waypoint is None or self.current_pose is None:
return

# Calculate distance to waypoint
dx = self.current_waypoint.pose.position.x - self.current_pose.pose.position.x
dy = self.current_waypoint.pose.position.y - self.current_pose.pose.position.y
distance = np.sqrt(dx**2 + dy**2)

# If close to waypoint, consider it reached
if distance < 0.1:
self.locomotion_state = LocomotionState.IDLE

def send_zero_command(self):
"""Send zero commands to stop the robot"""
# Publish zero joint trajectory
traj_msg = JointTrajectory()
traj_msg.header.stamp = self.get_clock().now().to_msg()
traj_msg.header.frame_id = 'base_link'
traj_msg.joint_names = self.joint_names

point = JointTrajectoryPoint()
point.positions = [0.0, 0.0, 0.0, 0.0, 0.0]
point.velocities = [0.0, 0.0, 0.0, 0.0, 0.0]
point.accelerations = [0.0, 0.0, 0.0, 0.0, 0.0]
point.effort = [0.0, 0.0, 0.0, 0.0, 0.0]
point.time_from_start = Duration(sec=0, nanosec=100000000) # 0.1 seconds

traj_msg.points.append(point)
self.joint_cmd_pub.publish(traj_msg)

Step 6: Create a Goal Publisher​

Create the goal publisher script (scripts/goal_publisher.py):

#!/usr/bin/env python3

import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped
import sys
import time

class GoalPublisher(Node):
def __init__(self):
super().__init__('goal_publisher')
self.publisher = self.create_publisher(PoseStamped, 'goal_pose', 10)

def publish_goal(self, x, y):
goal = PoseStamped()
goal.header.stamp = self.get_clock().now().to_msg()
goal.header.frame_id = 'map'
goal.pose.position.x = x
goal.pose.position.y = y
goal.pose.position.z = 0.0
goal.pose.orientation.w = 1.0 # No rotation

self.publisher.publish(goal)
self.get_logger().info(f'Published goal: ({x}, {y})')

def main(args=None):
rclpy.init(args=args)

goal_publisher = GoalPublisher()

# Get goal coordinates from command line arguments
if len(sys.argv) < 3:
print("Usage: python3 goal_publisher.py <x> <y>")
print("Example: python3 goal_publisher.py 1.0 2.0")
goal_publisher.destroy_node()
rclpy.shutdown()
return

x = float(sys.argv[1])
y = float(sys.argv[2])

# Publish goal after a short delay to ensure system is ready
time.sleep(2.0)
goal_publisher.publish_goal(x, y)

rclpy.spin(goal_publisher)

goal_publisher.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Step 7: Create the Launch File​

Create launch/control_pipeline.launch.py:

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, RegisterEventHandler
from launch.event_handlers import OnProcessStart
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node, SetParameter
from launch_ros.substitutions import FindPackageShare
from ament_index_python.packages import get_package_share_directory

def generate_launch_description():
# Launch arguments
use_sim_time = DeclareLaunchArgument(
'use_sim_time',
default_value='false',
description='Use simulation time if true'
)

# Get URDF file path
urdf_file = PathJoinSubstitution([
FindPackageShare('simple_humanoid_control'),
'urdf',
'simple_humanoid.urdf'
])

# Robot state publisher
robot_state_publisher = Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
parameters=[
{'robot_description': open(get_package_share_directory('simple_humanoid_control') + '/urdf/simple_humanoid.urdf').read()},
{'use_sim_time': LaunchConfiguration('use_sim_time')}
],
remappings=[
('/tf', 'tf'),
('/tf_static', 'tf_static')
]
)

# Path planner node
path_planner = Node(
package='simple_humanoid_control',
executable='path_planner',
name='simple_path_planner',
parameters=[
PathJoinSubstitution([
FindPackageShare('simple_humanoid_control'),
'config',
'humanoid_params.yaml'
]),
{'use_sim_time': LaunchConfiguration('use_sim_time')}
],
remappings=[
('/scan', '/laser_scan'), # Remap to match simulation
],
output='screen'
)

# Controller node
controller = Node(
package='simple_humanoid_control',
executable='controller',
name='humanoid_controller',
parameters=[
PathJoinSubstitution([
FindPackageShare('simple_humanoid_control'),
'config',
'humanoid_params.yaml'
]),
{'use_sim_time': LaunchConfiguration('use_sim_time')}
],
output='screen'
)

return LaunchDescription([
use_sim_time,
robot_state_publisher,
path_planner,
controller
])

Step 8: Create Package Configuration Files​

Create CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(simple_humanoid_control)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
find_package(rclpy REQUIRED)
find_package(std_msgs REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(nav_msgs REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(trajectory_msgs REQUIRED)
find_package(builtin_interfaces REQUIRED)

# Install Python modules
ament_python_install_package(${PROJECT_NAME})

# Install Python executables
install(PROGRAMS
scripts/goal_publisher.py
DESTINATION lib/${PROJECT_NAME}
)

# Install launch files
install(DIRECTORY
launch
config
urdf
DESTINATION share/${PROJECT_NAME}/
)

ament_package()

Create package.xml:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>simple_humanoid_control</name>
<version>0.0.1</version>
<description>A simple ROS 2 control pipeline for humanoid robots</description>
<maintainer email="example@todo.todo">TODO</maintainer>
<license>TODO: License declaration</license>

<depend>rclpy</depend>
<depend>std_msgs</depend>
<depend>geometry_msgs</depend>
<depend>nav_msgs</depend>
<depend>sensor_msgs</depend>
<depend>trajectory_msgs</depend>
<depend>builtin_interfaces</depend>

<exec_depend>robot_state_publisher</exec_depend>

<test_depend>ament_copyright</test_depend>
<test_depend>ament_flake8</test_depend>
<test_depend>ament_pep257</test_depend>
<test_depend>python3-pytest</test_depend>

<export>
<build_type>ament_python</build_type>
</export>
</package>

Step 9: Building and Running the Pipeline​

To build and run the pipeline:

  1. Navigate to your ROS 2 workspace
  2. Build the package: colcon build --packages-select simple_humanoid_control
  3. Source the workspace: source install/setup.bash
  4. Launch the pipeline: ros2 launch simple_humanoid_control control_pipeline.launch.py
  5. Send a goal: python3 scripts/goal_publisher.py 1.0 1.0

Testing the Pipeline​

Step 1: Verify Components​

  • Check that all nodes are running: ros2 node list
  • Check topic connections: ros2 topic list
  • Verify parameter values: ros2 param list

Step 2: Visualize the Robot​

Launch RViz to visualize the robot:

ros2 run rviz2 rviz2

Then add robot model visualization and path display.

Step 3: Monitor Performance​

Monitor key metrics:

  • Control loop frequency
  • Path planning computation time
  • Joint trajectory execution

Learning Objectives Achieved​

This mini-project successfully demonstrates:

  1. Integration of ROS 2 concepts (nodes, topics, parameters)
  2. Implementation of robot control using rclpy
  3. URDF-based robot modeling
  4. Launch file configuration for complex systems
  5. Parameter management for physical AI systems

Extending the Pipeline​

Consider these extensions:

  1. Add more sophisticated path planning (A*, RRT)
  2. Implement inverse kinematics for more realistic locomotion
  3. Add perception nodes for obstacle detection
  4. Include state estimation (Kalman filtering)
  5. Add machine learning components for adaptive control

Learning Objectives​

After completing this mini-project, you will have:

  • Built a complete ROS 2 control pipeline
  • Integrated multiple ROS 2 components and concepts
  • Implemented parameterized controllers for humanoid robots
  • Configured a complete robot system with launch files
  • Gained experience in Physical AI system architecture

Next Steps​

Module 1 has provided the foundational knowledge for ROS 2-based Physical AI systems. In Module 2, we'll explore Digital Twins using Gazebo and Unity, building simulation environments where you can test and validate the controllers we've developed.

💬
🤖
ROBO-ASSISTANT
Hello! I'm your AI assistant for Physical AI & Humanoid Robotics. How can I help you today?