Stage 10 · Lesson 09/16

ROS 2 & Robot Software Architecture (Fundamentals) · Lesson 09

Launch Files

Est. 50–70 min

Why

Why this lesson matters

Think of a train leaving a station. The guard does not walk to every coach and start it. She checks the train, raises the green flag, and the whole train moves together. A launch file is that green flag: it describes which nodes to start, with which names, namespaces and parameters — and starts them all at once.

By the end of this lesson you will be able to: explain what the launch system does; read and write a Python launch file with Node, namespaces, parameters and remaps; write the same file in XML; add launch arguments with DeclareLaunchArgument and LaunchConfiguration; install launch files in a package; use respawn safely; and debug the usual launch errors.

An Indian Railways woman guard holding a green flag at a station
An Indian Railways guard ready with the green flag. One signal and the whole train moves — a launch file does the same for your nodes.Photo: UY Scuti · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

How launch works

What the docs say launch is for

The Jazzy Launch concept page says a ROS 2 system usually has many nodes in many processes (even on different machines). Starting each by hand gets cumbersome quickly, so the launch system automates running many nodes with a single command. It describes what programs to run, where, with what arguments, and it monitors the processes it started and can react when they change.

Fact from the docsWhat it means for our arm
Launch files can be written in XML, YAML or PythonWe show Python and XML; pick one style per project
Run them with ros2 launchros2 launch arm_bringup arm_launch.py
The package is launch_ros, built on the general launch frameworkImport Node from launch_ros.actions
A Python launch file defines generate_launch_description() returning a LaunchDescriptionThe whole arm is one list of actions
Name Python files ending in launch.py so ros2 launch recognises and autocompletes themarm_launch.py, not arm.py
By convention, launch files sit in a launch/ folder of the packagearm_bringup/launch/

The official turtlesim mimic example

The Jazzy tutorial starts two turtlesim windows in different namespaces (turtlesim1, turtlesim2) so their topics do not clash, and a mimic node whose topics are remapped so turtle 2 copies turtle 1. Namespaces and remaps are the two tools you will use most.

turtlesim_mimic_launch.py (from the Jazzy “Creating a launch file” tutorial) · Python
from launch import LaunchDescription
from launch_ros.actions import Node


def generate_launch_description():
    return LaunchDescription([
        Node(
            package='turtlesim',
            namespace='turtlesim1',
            executable='turtlesim_node',
            name='sim',
            arguments=['--ros-args', '--log-level', 'info']
        ),
        Node(
            package='turtlesim',
            namespace='turtlesim2',
            executable='turtlesim_node',
            name='sim',
            ros_arguments=['--log-level', 'warn']
        ),
        Node(
            package='turtlesim',
            executable='mimic',
            name='mimic',
            remappings=[
                ('/input/pose', '/turtlesim1/turtle1/pose'),
                ('/output/cmd_vel', '/turtlesim2/turtle1/cmd_vel'),
            ]
        )
    ])

Launch arguments: one file, many robots

DeclareLaunchArgument defines an argument that can be passed from the console; LaunchConfiguration reads its value anywhere in the description. You pass values as name:=value, and ros2 launch <pkg> <file> --show-args lists them. In XML, <arg> declares and $(var name) reads.

Visual

Visualise it: one launch file, many nodes

One launch file, many nodes: change arguments and watch the node list and parameters change.

Interactive · Launch & parameter lab

ROS 2 communication simulator — educational only (not a live ros2 launch / param)

Launch file starting multiple nodesParameters configuring a node

Running: none

  • Launch or tweak params to see the event log.

Code lab

Code lab: a toy launcher, then the real arm launch file

launch_sim.py (plain Python, no ROS needed) “launches” our three arm nodes, changes namespace and port with arguments, restarts a crashing gripper node at most twice, and stops on a typo in an executable name. Run python3 launch_sim.py.

launch_sim.py · Python
"""launch_sim.py - a toy "ros2 launch" (plain Python, no ROS 2 needed).

Ideas from the ROS 2 Jazzy launch docs and the launch source code:
  * one launch file describes many nodes: package, executable, name, namespace, parameters, remaps
  * launch arguments (name:=value) change the description without editing the file
  * launch watches the processes it started; respawn=True restarts a node that died,
    respawn_max_retries limits how many times
This is a teaching model, not the real launch system.
"""
INSTALLED = {
    "arm_control": {"joint_state", "gripper_service", "move_joint_server", "shoulder_angle"},
    "turtlesim": {"turtlesim_node", "mimic"},
}


def node(package, executable, name, params=None, remaps=None, respawn=False, max_retries=-1, crash_after=None):
    return dict(package=package, executable=executable, name=name, params=params or {},
                remaps=remaps or {}, respawn=respawn, max_retries=max_retries, crash_after=crash_after)


def arm_launch(args):
    """Our arm_launch.py, as plain data. args are the launch arguments."""
    ns = args.get("ns", "arm1")
    port = args.get("port", "")
    return [
        node("arm_control", "joint_state", "joint_state_node", {"rate_hz": 20.0}),
        node("arm_control", "gripper_service", "gripper_service", {}, respawn=True, max_retries=2,
             crash_after=args.get("gripper_crash_after")),
        node("arm_control", args.get("server_exec", "move_joint_server"), "move_joint_server",
             {"port": port, "start_deg": 90.0}),
    ], ns


def ros2_launch(title, args):
    print(f"\n=== ros2 launch arm_bringup arm_launch.py {' '.join(f'{k}:={v}' for k, v in args.items())} ===")
    print(f"  ({title})")
    nodes, ns = arm_launch(args)
    names = [f"/{ns}/{n['name']}" for n in nodes]
    if len(set(names)) != len(names):
        print("  WARNING: two nodes share a full name - rename or use namespaces")
    pid = 4100
    running = []
    for i, n in enumerate(nodes, 1):
        if n["executable"] not in INSTALLED.get(n["package"], set()):
            print(f"  [ERROR] [launch]: executable '{n['executable']}' not found on the libexec directory"
                  f" of package '{n['package']}' -> check console_scripts and rebuild")
            print("  launch reports the error and shuts down the nodes it already started")
            return
        pid += 1
        tag = f"{n['executable']}-{i}"
        running.append((tag, n))
        hw = f" port='{n['params']['port']}'" if "port" in n["params"] else ""
        print(f"  [INFO] [{tag}]: process started with pid [{pid}]  -> /{ns}/{n['name']}{hw}")
    # watch the processes for 10 'seconds'
    for tag, n in running:
        if n["crash_after"] is None:
            continue
        retries = 0
        t = n["crash_after"]
        while True:
            print(f"  t={t:>4.1f}s [ERROR] [{tag}]: process has died [exit code 1]")
            if not n["respawn"] or (0 <= n["max_retries"] <= retries):
                print(f"         launch gives up on {tag}; the other nodes keep running")
                break
            retries += 1
            pid += 1
            print(f"         respawn {retries}/{n['max_retries']}: [INFO] [{tag}]: process started with pid [{pid}]")
            t += n["crash_after"]
            if t > 10:
                break
    print(f"  Ctrl+C -> launch sends SIGINT to all {len(running)} processes and waits for them to exit")


print("Part 1: start the whole arm with one command (no hardware)")
ros2_launch("defaults", {})

print("\nPart 2: same file, different arguments - second arm on the real serial port")
ros2_launch("arguments change namespace and port", {"ns": "arm2", "port": "/dev/ttyACM0"})

print("\nPart 3: the gripper node crashes every 3 s (loose USB cable)")
ros2_launch("respawn=True, respawn_max_retries=2", {"gripper_crash_after": 3.0})

print("\nPart 4: a typo in the executable name")
ros2_launch("move_joint_sever instead of move_joint_server", {"server_exec": "move_joint_sever"})

print("\nPart 5: why launch? count the commands")
manual = 3 * 3  # 3 nodes x (open terminal, source install/setup.bash, ros2 run ...)
print(f"  by hand: {manual} steps in 3 terminals, easy to forget a parameter")
print("  launch : 1 command, the same every time, arguments for what changes")

Output (run with python3 launch_sim.py)

Part 1: start the whole arm with one command (no hardware)

=== ros2 launch arm_bringup arm_launch.py  ===
  (defaults)
  [INFO] [joint_state-1]: process started with pid [4101]  -> /arm1/joint_state_node
  [INFO] [gripper_service-2]: process started with pid [4102]  -> /arm1/gripper_service
  [INFO] [move_joint_server-3]: process started with pid [4103]  -> /arm1/move_joint_server port=''
  Ctrl+C -> launch sends SIGINT to all 3 processes and waits for them to exit

Part 2: same file, different arguments - second arm on the real serial port

=== ros2 launch arm_bringup arm_launch.py ns:=arm2 port:=/dev/ttyACM0 ===
  (arguments change namespace and port)
  [INFO] [joint_state-1]: process started with pid [4101]  -> /arm2/joint_state_node
  [INFO] [gripper_service-2]: process started with pid [4102]  -> /arm2/gripper_service
  [INFO] [move_joint_server-3]: process started with pid [4103]  -> /arm2/move_joint_server port='/dev/ttyACM0'
  Ctrl+C -> launch sends SIGINT to all 3 processes and waits for them to exit

Part 3: the gripper node crashes every 3 s (loose USB cable)

=== ros2 launch arm_bringup arm_launch.py gripper_crash_after:=3.0 ===
  (respawn=True, respawn_max_retries=2)
  [INFO] [joint_state-1]: process started with pid [4101]  -> /arm1/joint_state_node
  [INFO] [gripper_service-2]: process started with pid [4102]  -> /arm1/gripper_service
  [INFO] [move_joint_server-3]: process started with pid [4103]  -> /arm1/move_joint_server port=''
  t= 3.0s [ERROR] [gripper_service-2]: process has died [exit code 1]
         respawn 1/2: [INFO] [gripper_service-2]: process started with pid [4104]
  t= 6.0s [ERROR] [gripper_service-2]: process has died [exit code 1]
         respawn 2/2: [INFO] [gripper_service-2]: process started with pid [4105]
  t= 9.0s [ERROR] [gripper_service-2]: process has died [exit code 1]
         launch gives up on gripper_service-2; the other nodes keep running
  Ctrl+C -> launch sends SIGINT to all 3 processes and waits for them to exit

Part 4: a typo in the executable name

=== ros2 launch arm_bringup arm_launch.py server_exec:=move_joint_sever ===
  (move_joint_sever instead of move_joint_server)
  [INFO] [joint_state-1]: process started with pid [4101]  -> /arm1/joint_state_node
  [INFO] [gripper_service-2]: process started with pid [4102]  -> /arm1/gripper_service
  [ERROR] [launch]: executable 'move_joint_sever' not found on the libexec directory of package 'arm_control' -> check console_scripts and rebuild
  launch reports the error and shuts down the nodes it already started

Part 5: why launch? count the commands
  by hand: 9 steps in 3 terminals, easy to forget a parameter
  launch : 1 command, the same every time, arguments for what changes

Try it: change launch arguments and parameters and see which nodes start with which values.

Interactive · Launch & parameter lab

ROS 2 communication simulator — educational only (not a live ros2 launch / param)

Launch file starting multiple nodesParameters configuring a node

Running: none

  • Launch or tweak params to see the event log.

arm_launch.py — the whole arm in one file

This uses the nodes from Lessons 5–7 through the console_scripts names we gave them in Lesson 8. ns and port are launch arguments. output='screen' prints node logs in the launch terminal (the launch source says the default is log).

arm_bringup/launch/arm_launch.py (ROS 2 Jazzy) · Python
"""arm_launch.py - start the AIHUB desk arm with one command (ROS 2 Jazzy).

ros2 launch arm_bringup arm_launch.py
ros2 launch arm_bringup arm_launch.py ns:=arm2 port:=/dev/ttyACM0
ros2 launch arm_bringup arm_launch.py --show-args
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node


def generate_launch_description():
    ns = LaunchConfiguration('ns')
    port = LaunchConfiguration('port')

    return LaunchDescription([
        DeclareLaunchArgument('ns', default_value='arm1',
                              description='Namespace for this arm'),
        DeclareLaunchArgument('port', default_value='',
                              description="Arduino serial port for the joint servo; '' = simulate"),

        # Publishes sensor_msgs/JointState (Lesson 5). Simulated: no port.
        Node(
            package='arm_control',
            executable='joint_state',
            name='joint_state_node',
            namespace=ns,
            parameters=[{'rate_hz': 20.0}],
            output='screen',
        ),
        # std_srvs/SetBool gripper (Lesson 6). Restart it if it dies, but at most twice.
        Node(
            package='arm_control',
            executable='gripper_service',
            name='gripper_service',
            namespace=ns,
            output='screen',
            respawn=True,
            respawn_delay=2.0,
            respawn_max_retries=2,
        ),
        # MoveJoint action server (Lesson 7). Only this node opens the serial port:
        # one serial port can be opened by one node at a time.
        Node(
            package='arm_control',
            executable='move_joint_server',
            name='move_joint_server',
            namespace=ns,
            parameters=[{'port': port, 'start_deg': 90.0}],
            output='screen',
        ),
    ])

The same arm in XML

arm_bringup/launch/arm_launch.xml · XML
<?xml version="1.0" encoding="UTF-8"?>
<!-- Same arm as arm_launch.py, written in XML.
     ros2 launch arm_bringup arm_launch.xml ns:=arm1 port:=/dev/ttyACM0 -->
<launch>
  <arg name="ns" default="arm1" description="Namespace for this arm"/>
  <arg name="port" default="" description="Arduino serial port; empty = simulate"/>

  <node pkg="arm_control" exec="joint_state" name="joint_state_node" namespace="$(var ns)" output="screen">
    <param name="rate_hz" value="20.0"/>
  </node>

  <node pkg="arm_control" exec="gripper_service" name="gripper_service" namespace="$(var ns)"
        output="screen" respawn="true" respawn_delay="2.0" respawn_max_retries="2"/>

  <node pkg="arm_control" exec="move_joint_server" name="move_joint_server" namespace="$(var ns)" output="screen">
    <param name="port" value="$(var port)"/>
    <param name="start_deg" value="90.0"/>
  </node>
</launch>

Install the launch files with the package

The Jazzy “Integrating launch files into ROS 2 packages” tutorial adds the launch/ folder to data_files in setup.py (for CMake packages: install(DIRECTORY launch DESTINATION share/${PROJECT_NAME})). The “Creating a launch file” tutorial also recommends <exec_depend>ros2launch</exec_depend> in package.xml.

arm_bringup/setup.py (launch part) · Python
# arm_bringup/setup.py - install every file in launch/ (from the Jazzy
# "Integrating launch files into ROS 2 packages" tutorial)
import os
from glob import glob
from setuptools import find_packages, setup

package_name = 'arm_bringup'

setup(
    name=package_name,
    # ...
    data_files=[
        ('share/ament_index/resource_index/packages', ['resource/' + package_name]),
        ('share/' + package_name, ['package.xml']),
        (os.path.join('share', package_name, 'launch'), glob('launch/*')),
    ],
    # ...
)

# arm_bringup/package.xml - add:
#   <exec_depend>ros2launch</exec_depend>
#   <exec_depend>arm_control</exec_depend>
Build and run · Shell
cd ~/arm_ws
colcon build --symlink-install
# new terminal
source install/setup.bash

ros2 launch arm_bringup arm_launch.py --show-args
ros2 launch arm_bringup arm_launch.py                     # simulate, /arm1
ros2 launch arm_bringup arm_launch.py ns:=arm2 port:=/dev/ttyACM0

# in another terminal, check what started
ros2 node list
ros2 run rqt_graph rqt_graph

Real world

Launch files in the real world

  • turtlesim mimic (official tutorial): two simulators and a mimic node from one file, using namespaces and remaps.
  • Robot arms: a “bringup” launch file starts drivers, state publishers and controllers; a second one adds planning or vision.
  • Many robots, one file: warehouses run the same launch file with a different namespace argument on every robot.
  • Labs and classrooms: a launch file is the lab manual in code — every student starts the same system the same way.
An orchestra on stage with a conductor in front
An orchestra with its conductor. Each musician plays their own part; the conductor starts them together and watches all of them. That is the launch system’s job for nodes.Photo: Sweetie candykim · CC0 · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: start the bench arm with one command

Same one-servo bench as Lessons 7–8 with servo_position.ino. This time nothing is started by hand: one ros2 launch brings up joint states, the gripper service (simulated) and the move-joint server on the real port.

Wiring (unchanged from Lesson 7)
FromToNote
Servo signalArduino D9Signal only
Servo + (red)Separate 5–6 V supply +Not the Arduino 5V pin or any GPIO
Servo − (brown/black)Supply −—
Supply −Arduino GNDCommon ground
Arduino USBROS 2 computer115200 baud
servo_position.ino (from Lesson 7, compile-checked for Arduino UNO) · Arduino C++
// servo_position.ino - one servo follows position commands "P<deg>" (e.g. P93.5) at up to ~50 Hz.
// Used by move_joint_server.py, which does the smooth cubic profile on the computer.
// Clamps to 10..170 deg and uses writeMicroseconds for finer steps than whole degrees.
// With no new commands the servo simply holds its last position.
// POWER: servo red (+) to a SEPARATE 5-6 V supply, never the Arduino 5V pin or a GPIO. Join grounds.
#include <Servo.h>

const int SERVO_PIN = 9;
const float MIN_DEG = 10.0, MAX_DEG = 170.0;
Servo joint;
char buf[16];
byte n = 0;

int degToUs(float d) { return (int)(544.0 + (2400.0 - 544.0) * d / 180.0); }  // Servo library default range

void setup() {
  Serial.begin(115200);
  joint.attach(SERVO_PIN);
  joint.writeMicroseconds(degToUs(90.0));
}

void loop() {
  while (Serial.available()) {
    char c = Serial.read();
    if (c == '\n') {
      buf[n] = 0;
      if (n > 1 && buf[0] == 'P') {
        float d = atof(buf + 1);
        if (d < MIN_DEG) d = MIN_DEG;
        if (d > MAX_DEG) d = MAX_DEG;
        joint.writeMicroseconds(degToUs(d));
      }
      n = 0;
    } else if (n < sizeof(buf) - 1) {
      buf[n++] = c;
    }
  }
}
  1. Dry run

    Servo supply off. ros2 launch arm_bringup arm_launch.py — three nodes should start in /arm1, all simulated.

  2. Check the graph

    ros2 node list and ros2 action list -t; you should see /arm1/move_joint.

  3. Real port

    Stop with Ctrl+C. Switch the servo supply on. ros2 launch arm_bringup arm_launch.py port:=/dev/ttyACM0

  4. Move slowly

    ros2 action send_goal /arm1/move_joint arm_interfaces/action/MoveJoint "{target_deg: 60.0, duration_s: 3.0}" --feedback

  5. Shut down

    Ctrl+C in the launch terminal stops every node it started. Then switch the servo supply off.

A three-socket power strip with an illuminated master switch
One switch powers every socket on the strip. A launch file is the software version — but for motors you still want a real switch that cuts their supply.Photo: Xofc · CC BY-SA 3.0 · Source: Wikimedia Commons · resized, converted to WebP

Debugging

Debugging launch files

SymptomLikely causeFix
file 'arm_launch.py' was not found in the share directoryLaunch folder not in data_files, or not rebuiltAdd the glob('launch/*') line, rebuild, re-source
executable … not foundWrong executable= or missing console_scriptsros2 pkg executables arm_control and copy the name
Two nodes fight over the same topicSame name/namespace for two armsUse the ns argument or a namespace=
Argument ignoredTypo in name:=value or argument not declared--show-args lists what the file accepts
No node logs in the terminalOutput goes to the log by defaultAdd output='screen'
“Could not open port” in one nodeTwo nodes were given the same serial portGive the port to one node only
A node restarts foreverrespawn=True with no limitSet respawn_max_retries and fix the crash

Think

Think about it

Think

Your arm’s move-joint node crashes because the USB cable is loose. Should launch respawn it automatically? What could go wrong, and what would you do instead?

Experiment

Try it in the lab

About 40 minutes with Python; the ROS 2 steps need ROS 2 Jazzy with turtlesim and your arm_ws from Lesson 8; the bench step needs the Lesson 7 servo build.

Experiment

One command for the whole arm

You will need

  • `launch_sim.py` and Python 3
  • Launch & parameter lab (in your browser)
  • Optional: ROS 2 Jazzy, turtlesim, `arm_ws`, Arduino UNO, hobby servo, separate 5–6 V supply

Steps

  1. Run `launch_sim.py`. In Part 3 change `max_retries` to 0 and to -1. What changes, and why is -1 risky?
  2. Add a fourth node `shoulder_angle` to `arm_launch()` in the simulator. Give it the same port as the server — what would happen on a real robot?
  3. With ROS 2: save the turtlesim mimic launch file, run it, and publish to `/turtlesim1/turtle1/cmd_vel` as in the tutorial. Both turtles should move.
  4. With ROS 2: add `arm_launch.py` to `arm_bringup`, build, and run with `--show-args`, then with `ns:=arm2`.
  5. With ROS 2: run the XML version and compare `ros2 node list` with the Python version.
  6. Bench: launch with the real port and send a slow goal.

Interactive · Launch & parameter lab

ROS 2 communication simulator — educational only (not a live ros2 launch / param)

Launch file starting multiple nodesParameters configuring a node

Running: none

  • Launch or tweak params to see the event log.

Launch turns a page of terminal commands into one repeatable command. Arguments handle what changes between robots; namespaces keep them apart.

Knowledge check

Check your understanding

Knowledge check

1. What is the launch system for?

2. Which formats can ROS 2 launch files use?

3. A Python launch file must define…

4. In the mimic example, why are the two turtlesim nodes in different namespaces?

5. How do you pass a launch argument from the terminal?

6. `ros2 launch arm_bringup arm_launch.py` says the file is not found. Most likely?

7. Which node is safest to respawn automatically?

Mini assignment

Hands-on assignment

Mini assignment

A bringup launch file for your 6DOF arm

Write the launch file that starts your arm’s software, with arguments for what changes between robots.

Deliverables

  • A table of every node your arm needs: package, executable, name, namespace, parameters, and whether it may respawn (with a reason).
  • Output of `launch_sim.py` after your experiment changes.
  • Optional (ROS 2): your `arm_launch.py`, the output of `--show-args`, and `ros2 node list` while it runs.
  • Optional (bench): a short video of the servo moving after a single `ros2 launch` command.

Do this, step by step

  1. Run python3 launch_sim.py and try max_retries 0 and -1; write what changes.
  2. Make a table of every node your arm needs: package, executable, name, namespace, parameters, respawn yes/no with reason.
  3. Add the shoulder_angle node with the same port as the server and write what would happen on a real robot.
  4. Optional with ROS 2: add arm_launch.py to arm_bringup, build, and run with --show-args and with ns:=arm2.
  5. Compare ros2 node list for the Python and XML launch versions.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Two nodes cannot hold one serial port at the same time — the second one fails to open it.
  2. Endless respawn hides a crash loop; a driver that keeps crashing should stop and be looked at.
  3. Launch arguments are for what changes between robots (namespace, port); keep everything else fixed.

Challenges (pick by level)

  • 🟢 Easy: Run the turtlesim mimic example in all three formats (XML, YAML, Python).
  • 🟡 Medium: Add a use_hw argument that sets the server’s port only when true.
  • 🟠 Hard-ish: Write a second launch file that includes arm_launch.py twice for /arm1 and /arm2 (look up IncludeLaunchDescription).
  • 🔴 Hard: Add a TimerAction that starts the move-joint server 3 s after the others and explain when a delay like that helps.
  • ⚫ Research: Read the ROS 2 launch design article and list which planned features exist in Jazzy and which do not yet.

Next step

Our launch file already passes rate_hz, port and start_deg. In Lesson 10 — Parameters & Configuration you will learn how parameters really work, change them while nodes run, and keep them in YAML files.

Look back: Lesson 8: ROS 2 Packages & Workspace. Next: Lesson 10: Parameters & Configuration. Related: Stage 3 — Linux & Dev Environment.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in