ROS 2 from zero

← Robot list · The basics

ROS 2 is the software that most research, service and mobile robots run on. This course starts from nothing: what ROS 2 is, nodes and topics, your first nodes in Python, services and actions, launch files, frames and the robot model, simulation, the big navigation and arm stacks, and a first complete project. You only need basic Python and a computer with Ubuntu.

How to follow this course

ROS 2 is learned with the keyboard. Each lesson gives commands and short programs: type them, run them, change a value and see what happens. Lessons 1 to 5 need only ROS 2; lessons 6 to 9 use a free simulator, so you do not need a real robot.

The programs of this course follow the official ROS 2 interfaces (Jazzy). The logic of the final project was checked by running it on simulated laser data; the commands depend on your installation, so read the error messages: the “classic mistakes” boxes cover the most frequent ones.

1

What ROS 2 is, and why robots use it

10 min
You will learn

what ROS 2 does for you, what it does not do, and how to install it and run your first two programs.

1.1 The problem ROS 2 solves

A robot runs many programs at the same time: one reads the camera, one reads the laser, one computes where the robot is, one plans the path, one drives the motors. They are written by different people, in different languages, and often run on different computers. They must talk to each other.

ROS 2 (Robot Operating System 2) is the free, open-source software that makes them talk. Despite its name it is not an operating system: it is installed on top of Linux (or Windows, macOS). It gives you three things:

WhatIn simple wordsExamples
The plumbingPrograms send each other messages without knowing where the other one runs.topics, services, actions
The toolsSee, record, replay and debug what happens inside the robot.ros2 commands, RViz, rosbag, Gazebo
The librariesReady-made, tested solutions to the hard problems.Nav2 (navigation), MoveIt 2 (arms), slam_toolbox (maps)
The key idea

With ROS 2 you do not write one big program. You write small programs that each do one job, and you connect them. You can then replace one of them (a real camera by a simulated one, your planner by a better one) without touching the others.

1.2 What ROS 2 is not

  • It is not a programming language: you write your nodes in Python or C++.
  • It does not replace the maths: the kinematics, the PID and the Kalman filter of the other courses are still there, inside the nodes.
  • It is not the safety system: an emergency stop never depends on ROS 2.

1.3 Versions (distributions)

ROS 2 is released once a year under a name. Some releases are supported for five years (LTS): choose one of these to learn. This course uses Jazzy Jalisco (2024, LTS, on Ubuntu 24.04); everything here also works on Humble (2022, LTS, Ubuntu 22.04) by replacing jazzy with humble. For a newer release, check docs.ros.org: the ideas of this course do not change.

ROS 1 is finished

The first ROS (ROS 1, last version “Noetic”) reached its end of life in 2025. Many old tutorials still use it: if you see roscore, rosrun or catkin_make, it is ROS 1. In ROS 2 the commands start with ros2 and the build tool is colcon.

1.4 Install it and say hello

The simplest way is a computer (or a virtual machine) with Ubuntu. The official guide on docs.ros.org gives the exact steps to add the ROS 2 package source; then:

# Ubuntu 24.04 + ROS 2 Jazzy (after adding the ROS 2 apt repository, see docs.ros.org)
sudo apt install ros-jazzy-desktop          # ROS 2, RViz, demos
sudo apt install python3-colcon-common-extensions

source /opt/ros/jazzy/setup.bash            # in every new terminal (or put it in ~/.bashrc)

ros2 run demo_nodes_cpp talker              # terminal 1: publishes "Hello World: 1, 2, 3..."
ros2 run demo_nodes_py listener             # terminal 2: prints what it hears

The talker and the listener are two separate programs. They found each other alone, with no address to configure: this is the plumbing of ROS 2 at work.

The most common beginner error

ros2: command not found means you forgot source /opt/ros/jazzy/setup.bash in this terminal. Every new terminal needs it.

Key terms

  • middleware
  • node
  • distribution
  • LTS
  • colcon
The essentials
  • ROS 2 is not an operating system: it is the software that lets the programs of a robot talk to each other, plus tools and libraries.
  • A robot is split into small programs (nodes) that each do one job.
  • In every new terminal: source /opt/ros/jazzy/setup.bash.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

What is ROS 2?

  1. A middleware with tools and libraries, installed on top of Linux
  2. An operating system that replaces Linux
  3. A programming language

Solution

ROS 2 is a middleware: it carries the messages between programs written in Python or C++, on top of an operating system.

Level 2 · Intermediate2

Jazzy came out in 2024 and is supported for 5 years. Until which year?

Solution

2024 + 5 = 2029. An LTS release gives you time to finish a project without changing version.

Level 3 · Professional3

You type ros2 topic list and get “ros2: command not found”. The most likely cause?

  1. The setup file was not sourced in this terminal
  2. No node is running
  3. The robot is switched off

Solution

The command itself is unknown, so ROS 2 is not loaded in this terminal: run source /opt/ros/jazzy/setup.bash.

Check yourself
  1. Is ROS 2 an operating system?

    No. It is a middleware and a set of tools and libraries, installed on top of an operating system such as Ubuntu.

  2. Why split a robot program into many small nodes?

    Each node does one job, can be tested alone, reused on another robot and replaced (for example by a simulated version) without changing the others.

  3. A tutorial tells you to type roscore. What does it tell you?

    It is a ROS 1 tutorial. ROS 2 has no roscore: the nodes discover each other.

2

Nodes, topics and messages

12 min
You will learn

how nodes exchange data with topics, what a message is, and the commands to look inside a running robot.

2.1 Publish and subscribe

A node is one running program. A topic is a named channel, like a radio station. A node that has data publishes it on a topic; every node that wants this data subscribes to the topic. The publisher does not know who listens, and it does not wait for an answer.

  • One topic can have several publishers and several subscribers.
  • Topics are for data that flows all the time: sensor readings, positions, speed commands.
  • Names look like paths: /scan, /cmd_vel, /camera/image_raw.

2.2 Messages have a type

Every topic carries messages of one type, known in advance. A type is a list of named fields. The most used ones:

TypeContainsTypical topic
std_msgs/msg/Stringa text/chatter
geometry_msgs/msg/Twista speed command: linear.x (m/s, forward) and angular.z (rad/s, turning)/cmd_vel
sensor_msgs/msg/LaserScanone turn of a laser scanner: a list of distances ranges, the first angle and the angle step/scan
sensor_msgs/msg/Imagea camera image/camera/image_raw
nav_msgs/msg/Odometrythe position and speed of the robot, from its wheels/odom
sensor_msgs/msg/JointStatethe angle and speed of every joint of an arm/joint_states
Units: always the same

ROS uses SI units everywhere: metres, seconds, radians, kilograms. Never degrees, never millimetres. The x axis of a robot points forward, y to the left, z up.

2.3 Look inside a running robot

Keep the talker and the listener of lesson 1 running, open a third terminal, and try:

ros2 node list                    # which nodes are running?
ros2 topic list -t                # which topics exist, and their message type
ros2 topic echo /chatter          # print the messages of a topic
ros2 topic hz /chatter            # how many messages per second?
ros2 topic info /chatter -v       # who publishes, who subscribes, with which QoS
ros2 interface show geometry_msgs/msg/Twist    # what is inside a message type

# publish by hand: drive a robot forward at 0.2 m/s while turning at 0.5 rad/s, 10 times per second
ros2 topic pub -r 10 /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.2}, angular: {z: 0.5}}"

rqt_graph                         # draw the graph of nodes and topics

These few commands are how you debug 90 % of ROS 2 problems: is the node running, is the topic there, does data flow, at which rate, with the right type?

2.4 Quality of service (QoS), in short

Each publisher and subscriber chooses how messages are delivered. Two settings matter at the beginning:

SettingChoiceUse it for
Reliabilityreliable: lost messages are sent againcommands, states, maps
Reliabilitybest effort: a lost message is forgotten, the next one comes soonfast sensors: laser, camera, IMU
History depthhow many messages wait if the subscriber is slow (often 10)every topic
A topic with no data? Check the QoS

A reliable subscriber does not receive anything from a best effort publisher: the two are not compatible, and there is no error message. If ros2 topic echo shows data but your node receives nothing, compare the QoS with ros2 topic info -v.

Key terms

  • node
  • topic
  • publisher
  • subscriber
  • message type
  • quality of service (QoS)
The essentials
  • A node publishes messages on a topic; any node can subscribe to it. Nobody answers.
  • Each topic has one message type. Units are always metres, seconds and radians.
  • ros2 topic list / echo / hz / info show what really happens.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

A topic carries 20 messages per second. Time between two messages (ms)?

Solution

1 / 20 = 0.05 s = 50 ms.

Level 2 · Intermediate2

A laser scan has 360 distances of 4 bytes each, 10 times per second. Data rate for the distances (kB/s, with 1 kB = 1000 bytes)?

Solution

360 × 4 = 1440 bytes per scan; × 10 = 14 400 bytes/s = 14.4 kB/s. A camera is thousands of times heavier: this is why images often use best effort.

Level 3 · Professional3

A laser driver publishes in best effort. Your node subscribes in reliable. What happens?

  1. Your node receives nothing, with no error
  2. Your node receives everything
  3. The driver crashes

Solution

A reliable subscriber asks for more than a best effort publisher offers: they are not compatible and do not connect. Subscribe with the sensor QoS.

Check yourself
  1. Does a publisher know which nodes receive its messages?

    No. It publishes on the topic; any number of nodes (zero, one, many) can subscribe.

  2. In a Twist message, which fields drive a wheeled robot forward and make it turn?

    linear.x in m/s (forward) and angular.z in rad/s (turn, positive to the left).

  3. Which command shows how many messages per second a topic carries?

    ros2 topic hz /name.

3

Your first nodes in Python

14 min
You will learn

to create a workspace and a package, write a publisher and a subscriber with rclpy, build them and run them.

3.1 Workspace and package

  • A package is a folder with your nodes and two description files (package.xml, setup.py). It is the unit you share and install.
  • A workspace is a folder that holds your packages in src/. The tool colcon builds them all.
mkdir -p ~/ros2_ws/src && cd ~/ros2_ws/src
ros2 pkg create my_robot --build-type ament_python --dependencies rclpy std_msgs

# put talker.py and listener.py in my_robot/my_robot/, then declare them in setup.py:
#   entry_points={'console_scripts': [
#       'talker = my_robot.talker:main',
#       'listener = my_robot.listener:main',
#   ]},

cd ~/ros2_ws
colcon build --symlink-install     # build every package of the workspace
source install/setup.bash          # make the new package visible in this terminal

ros2 run my_robot talker           # terminal 1
ros2 run my_robot listener         # terminal 2 (source install/setup.bash first)

3.2 A publisher

File my_robot/my_robot/talker.py. Read it from top to bottom: a node is a class; it creates a publisher and a timer; the timer calls tick(), which publishes one message.

import rclpy
from rclpy.node import Node
from std_msgs.msg import String


class Talker(Node):
    def __init__(self):
        super().__init__('talker')                               # the name of the node
        self.pub = self.create_publisher(String, 'chatter', 10)  # type, topic, queue size
        self.timer = self.create_timer(0.5, self.tick)           # call tick() every 0.5 s
        self.count = 0

    def tick(self):
        msg = String()
        msg.data = f'Hello robot: {self.count}'
        self.pub.publish(msg)
        self.get_logger().info(f'I said: "{msg.data}"')
        self.count += 1


def main():
    rclpy.init()
    node = Talker()
    try:
        rclpy.spin(node)             # wait and run the callbacks until Ctrl+C
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.try_shutdown()


if __name__ == '__main__':
    main()

3.3 A subscriber

File my_robot/my_robot/listener.py. The subscriber gives ROS 2 a function, called a callback: ROS 2 calls it each time a message arrives.

import rclpy
from rclpy.node import Node
from std_msgs.msg import String


class Listener(Node):
    def __init__(self):
        super().__init__('listener')
        # heard() is called each time a message arrives on the topic "chatter"
        self.sub = self.create_subscription(String, 'chatter', self.heard, 10)

    def heard(self, msg):
        self.get_logger().info(f'I heard: "{msg.data}"')


def main():
    rclpy.init()
    node = Listener()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.try_shutdown()


if __name__ == '__main__':
    main()
How a node really works

rclpy.spin(node) is a loop that waits. When a timer fires or a message arrives, it runs the matching callback, then waits again. So a callback must be short: while it runs, the node does nothing else. Never put time.sleep(5) or a long while loop inside a callback.

3.4 The pattern of every robot node

  1. Subscribe to the sensors: each callback only stores the last value.
  2. A timer at a fixed rate (10 to 100 Hz) reads these values, computes, and publishes the command.
  3. This is the loop “sense, think, act” of the first course, written with ROS 2. You will use it in lesson 9.
Three classic mistakes
  • You changed the code but nothing changes: you forgot colcon build (or use --symlink-install once, so Python files are linked, not copied).
  • Package 'my_robot' not found: you forgot source install/setup.bash in this terminal.
  • No executable found: the node is missing in entry_points of setup.py.

Python (rclpy) is perfect to learn and for most nodes. C++ (rclcpp) has the same ideas and the same names; it is used when speed matters (drivers, control loops, image processing).

Key terms

  • workspace
  • package
  • rclpy
  • callback
  • timer
  • spin
The essentials
  • A node is a class: it creates publishers, subscribers and timers.
  • ROS 2 calls your callbacks when a message arrives or a timer fires; keep them short.
  • Build with colcon build, then source install/setup.bash, then ros2 run.
Messages arrive 10 times per second. A slow callback fills the queue of 10 in 1.5 s.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

create_timer(0.5, self.tick): how many times per second is tick called?

Solution

1 / 0.5 = 2 Hz.

Level 2 · Intermediate2

You edited talker.py, ran colcon build, but ros2 run my_robot talker says the package is not found. What is missing?

  1. source install/setup.bash
  2. rclpy.spin()
  3. A second terminal

Solution

The terminal does not know the workspace yet: source install/setup.bash.

Level 3 · Professional3

Messages arrive at 10 Hz. Your callback takes 0.3 s. The queue holds 10 messages. After how many seconds is it full?

Hint

Each second 10 messages arrive and 1 / 0.3 are processed.

Solution

Processed: 1 / 0.3 = 3.33 per second. The queue grows by 10 − 3.33 = 6.67 per second: 10 / 6.67 = 1.5 s. After that, messages are dropped and the robot reacts to old data.

Check yourself
  1. What does rclpy.spin(node) do?

    It waits, and runs the callbacks of the node (timers, messages) each time one is due, until the program is stopped.

  2. Why must a callback be short?

    While one callback runs, the node cannot run the others: messages wait and timers are late.

  3. After colcon build, which command makes your package visible in a terminal?

    source install/setup.bash, from the workspace folder.

4

Services, actions and parameters

13 min
You will learn

the three other ways nodes communicate, and how to choose between a topic, a service and an action.

4.1 Four tools, four jobs

ToolLike…How it worksUse it for
Topica radio stationone way, all the time, nobody answerssensor data, speed commands
Servicea phone call with a quick questionone request, one answer, right away“switch the light on”, “save the map”, “compute this”
Actionordering a pizza: you follow the delivery and can cancela goal, then progress reports, then a result“go to the kitchen”, “move the arm along this path”
Parametera setting of the nodea named value, read at start or changed while runningmaximum speed, gains, name of a file
How to choose
  • Data that flows without being asked → topic.
  • A question with a quick answer (less than a second) → service.
  • A task that takes time, that you want to follow or cancel → action.

4.2 A service and a parameter in Python

This node offers the service add_two_ints: it receives two numbers and answers with their sum. It also has a parameter offset. (Add example_interfaces to the dependencies in package.xml, and the node to setup.py.)

import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts      # request: a, b   response: sum


class Adder(Node):
    def __init__(self):
        super().__init__('adder')
        self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add)
        self.declare_parameter('offset', 0)          # a parameter, with its default value

    def add(self, request, response):
        offset = self.get_parameter('offset').value
        response.sum = request.a + request.b + offset
        self.get_logger().info(f'{request.a} + {request.b} (+ {offset}) = {response.sum}')
        return response


def main():
    rclpy.init()
    node = Adder()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.try_shutdown()


if __name__ == '__main__':
    main()

Call it from the terminal, then change the parameter while the node runs:

ros2 run my_robot adder                                   # terminal 1: the server

ros2 service list -t                                      # terminal 2
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 2, b: 3}"
#   -> response: example_interfaces.srv.AddTwoInts_Response(sum=5)

ros2 param list /adder
ros2 param set /adder offset 10                           # change the parameter while the node runs
ros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 2, b: 3}"
#   -> sum=15

ros2 action list -t                                       # the actions, if a node offers some

4.3 Actions: goal, feedback, result

You will rarely write an action server at the beginning, but you will call them all the time: the navigation stack offers NavigateToPose, the arm stack offers FollowJointTrajectory. From the terminal: ros2 action send_goal /name type "{…}" --feedback.

4.4 Interfaces: the three kinds of files

FileDescribesParts
.msga topic messagethe fields
.srva servicerequest --- response
.actionan actiongoal --- result --- feedback

ros2 interface show prints any of them. Use the standard interfaces whenever one fits: your node then works with every existing tool.

Key terms

  • service
  • request / response
  • action
  • goal / feedback / result
  • parameter
  • interface
The essentials
  • Topic: data that flows. Service: a quick question and its answer. Action: a long task you can follow and cancel.
  • A parameter is a named setting of a node; it can be changed while the node runs.
  • Use the standard interfaces whenever one fits.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

“Is the gripper open?” (answer in 10 ms). Which tool?

  1. A service
  2. An action
  3. A launch file

Solution

A quick question with one answer: a service.

Level 2 · Intermediate2

With the node of the lesson and offset = 10, you call the service with a = 2 and b = 3. Sum?

Solution

2 + 3 + 10 = 15. The parameter changed the behaviour without restarting the node.

Level 3 · Professional3

“Move the arm along this 8-second trajectory, and stop if I ask.” Which tool?

  1. An action
  2. A service
  3. A parameter

Solution

A long task with progress and cancellation: an action (here FollowJointTrajectory).

Check yourself
  1. “Navigate to the charging station” takes 40 s and must be cancellable. Topic, service or action?

    An action: a long task with feedback and cancellation.

  2. Why not use a service to read a laser scanner 10 times per second?

    Data that flows all the time belongs on a topic: the driver publishes, and every node that needs it subscribes.

  3. What is a parameter?

    A named setting of a node (a number, a text, a boolean), given at start or changed while the node runs.

5

Launch files: start a whole robot with one command

10 min
You will learn

to start many nodes at once with their parameters, and to rename topics and group robots without changing the code.

5.1 Why launch files

A real robot runs 20 to 50 nodes. Nobody opens 50 terminals. A launch file is a list of the nodes to start, with their settings. One command starts everything, and Ctrl+C stops everything.

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node


def generate_launch_description():
    return LaunchDescription([
        DeclareLaunchArgument('robot', default_value='r1'),   # ros2 launch ... robot:=r2

        Node(package='my_robot', executable='talker',
             namespace=LaunchConfiguration('robot'),           # topics become /r1/...
             remappings=[('chatter', 'news')],                 # (name in the code, name on the network)
             output='screen'),

        Node(package='my_robot', executable='listener',
             namespace=LaunchConfiguration('robot'),
             remappings=[('chatter', 'news')],
             output='screen'),

        Node(package='my_robot', executable='adder',
             parameters=[{'offset': 10}]),                     # or a YAML file
    ])
# the file is my_robot/launch/demo.launch.py; add to setup.py (data_files):
#   (os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')),
colcon build --symlink-install && source install/setup.bash

ros2 launch my_robot demo.launch.py                # starts the three nodes
ros2 launch my_robot demo.launch.py robot:=r2      # same nodes, for a second robot
ros2 launch my_robot demo.launch.py --show-args    # which arguments does it accept?

5.2 Three ways to adapt a node without touching its code

ToolWhat it changesExample
Parametersthe settings of the nodeparameters=[{'speed': 0.3}], or a YAML file
Remappingthe name of a topicthe node publishes scan, the robot expects front_laser/scan
Namespacea prefix on every name of the nodetwo robots: /r1/cmd_vel and /r2/cmd_vel
Why node code uses names without a slash

In lesson 3 the topic was 'chatter', not '/chatter'. A name without a leading slash is relative: it takes the namespace of the node. The same code then works for robot 1 and robot 2. A name that starts with / is absolute and ignores the namespace.

5.3 Parameters in a YAML file

When a node has many parameters, put them in a file config/params.yaml and give its path in parameters=[…]:

safe_driver:                 # the name of the node
  ros__parameters:
    speed: 0.15
    stop_distance: 0.40

Launch files can also include other launch files: this is how the big stacks start. One line includes the whole navigation system.

The layout of a tidy package
my_robot/
  package.xml          dependencies
  setup.py             nodes and installed files
  my_robot/            the Python nodes
  launch/              *.launch.py
  config/              *.yaml (parameters)
  urdf/                the model of the robot (lesson 6)

Key terms

  • launch file
  • launch argument
  • remapping
  • namespace
  • YAML
The essentials
  • A launch file starts many nodes with one command.
  • Parameters change the settings, remapping changes a topic name, a namespace adds a prefix to all the names.
  • Names without a leading slash follow the namespace: the same code works for several robots.
One launch file starts the same nodes twice: the namespace prefixes every relative name, so the two robots do not mix their topics.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

A launch file starts 3 nodes. You launch it once for each of 4 robots. How many nodes run?

Solution

3 × 4 = 12 nodes, started with 4 commands instead of 12.

Level 2 · Intermediate2

A node in the namespace r2 publishes on cmd_vel. Full name of the topic?

  1. /r2/cmd_vel
  2. /cmd_vel
  3. /cmd_vel/r2

Solution

A relative name takes the namespace as a prefix: /r2/cmd_vel.

Level 3 · Professional3

Your node subscribes to scan; the robot publishes front/scan. Which remapping do you write on your node?

  1. ('scan', 'front/scan')
  2. ('front/scan', 'scan')

Solution

The pair is (name in the code, name on the network): ('scan', 'front/scan').

Check yourself
  1. Two identical robots must run the same nodes without mixing their topics. What do you use?

    A namespace for each robot (for example r1 and r2), given in the launch file.

  2. A driver publishes on scan but your node listens to laser. How do you connect them without editing the code?

    With a remapping in the launch file: ('laser', 'scan') on your node.

  3. In a node running in the namespace r1, which topic does the name /cmd_vel give?

    /cmd_vel: a name starting with a slash is absolute. The relative name cmd_vel would give /r1/cmd_vel.

6

Frames and the robot model: tf2 and URDF

14 min
You will learn

how ROS 2 keeps track of every frame of the robot, and how to describe a robot in a URDF file.

6.1 The question tf2 answers

The camera sees a cup at 0.6 m in front of it. Where is the cup for the gripper? For the map? You know the answer from the modelling course: multiply the homogeneous matrices from one frame to the other. tf2 is the ROS 2 library that does it for you, for all the frames, all the time.

Every frame has a name and exactly one parent: the frames form a tree. Each link of the tree is a transform (a translation and a rotation) published on the topics /tf and /tf_static.

FrameWhat it is
base_linkthe body of the robot: x forward, y left, z up
odomwhere the robot started. odom → base_link comes from the wheels: smooth, but it drifts.
mapthe fixed frame of the map. map → odom comes from the localisation: it corrects the drift, with small jumps.
laser_link, camera_link…one frame per sensor, fixed on the body

6.2 URDF: the robot in a file

A URDF file describes the robot as links (rigid parts) joined by joints, exactly the chain of the first course. Each joint says: its parent link, its child link, where it is (origin), around which axis it moves, and its type (revolute, prismatic, continuous, fixed). Here is the 2-axis arm of the maths course:

<?xml version="1.0"?>
<robot name="two_axis_arm">
  <link name="base_link">
    <visual><geometry><cylinder radius="0.10" length="0.05"/></geometry></visual>
  </link>

  <link name="link1">
    <visual>
      <origin xyz="0.25 0 0"/>                       <!-- the box is centred in the middle of the link -->
      <geometry><box size="0.50 0.05 0.05"/></geometry>
    </visual>
  </link>

  <link name="link2">
    <visual>
      <origin xyz="0.20 0 0"/>
      <geometry><box size="0.40 0.04 0.04"/></geometry>
    </visual>
  </link>

  <joint name="joint1" type="revolute">              <!-- theta1 -->
    <parent link="base_link"/> <child link="link1"/>
    <origin xyz="0 0 0.05"/> <axis xyz="0 0 1"/>
    <limit lower="-3.14" upper="3.14" effort="10" velocity="2"/>
  </joint>

  <joint name="joint2" type="revolute">              <!-- theta2, at the end of link1 (L1 = 0.5 m) -->
    <parent link="link1"/> <child link="link2"/>
    <origin xyz="0.5 0 0"/> <axis xyz="0 0 1"/>
    <limit lower="-2.6" upper="2.6" effort="10" velocity="2"/>
  </joint>
</robot>

The node robot_state_publisher reads the URDF and the joint angles (topic /joint_states) and publishes all the frames of the robot on tf: it computes the forward kinematics for you.

sudo apt install ros-jazzy-urdf-tutorial ros-jazzy-tf2-tools

ros2 launch urdf_tutorial display.launch.py model:=$PWD/robot.urdf
#   -> RViz shows the arm, and a small window with one slider per joint

ros2 run tf2_ros tf2_echo base_link link2          # where is link2, seen from the base?
ros2 run tf2_tools view_frames                     # writes frames.pdf: the whole tree

# a fixed frame, for example a camera 0.2 m in front of the base and 0.5 m above it
ros2 run tf2_ros static_transform_publisher --x 0.2 --z 0.5 --frame-id base_link --child-frame-id camera_link
Check the forward kinematics yourself

Set joint1 = 0.5 rad and joint2 = 0.8 rad with the sliders. The origin of link2 is at the end of link 1: x = 0.5 cos 0.5 = 0.439 m, y = 0.5 sin 0.5 = 0.240 m, z = 0.05 m. tf2_echo base_link link2 must print the same translation. It is the formula x = L₁ cos θ₁ of the maths course, computed by ROS 2.

A URDF describes the robot as a chain (a tree) of links joined by joints. Each joint names its parent and its child link, where it sits and how it moves.

6.3 RViz: see what the robot thinks

RViz is the 3D viewer of ROS 2. It does not simulate anything: it draws the data that the nodes publish (the robot model, the frames, the laser points, the map, the planned path). Choose the Fixed Frame at the top left (base_link, odom or map), then add displays.

Typical tf problems
  • “frame does not exist” or two separate trees: a link of the tree is missing. Look at the PDF of view_frames.
  • The sensor data appears at the wrong place: the origin of the sensor in the URDF is wrong (measure it on the real robot).
  • “extrapolation into the future”: the clocks of two computers differ, or simulated time is not enabled (use_sim_time).

Key terms

  • tf2
  • frame
  • transform
  • URDF
  • link / joint
  • robot_state_publisher
  • RViz
The essentials
  • tf2 keeps the tree of all the frames and gives the transform between any two of them.
  • Usual chain of a mobile robot: map → odom → base_link → sensors.
  • The URDF describes links and joints; robot_state_publisher turns it into frames.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

With the URDF of the lesson and joint1 = 1.0 rad, x of the origin of link2 (m)?

Solution

x = L₁ cos θ₁ = 0.5 × cos(1.0) = 0.5 × 0.540 = 0.27 m.

Level 2 · Intermediate2

The robot is at x = 3 m, y = 1 m in the map, facing along x. Its camera is 0.2 m in front of base_link. x of the camera in the map (m)?

Solution

The robot looks along x, so “in front” is +x: 3 + 0.2 = 3.2 m (y stays 1 m).

Level 3 · Professional3

Same robot, now turned by 90° (facing along +y). y of the camera in the map (m)?

Hint

Rotate the vector (0.2, 0) by 90°, then add the position of the robot.

Solution

(0.2, 0) turned by 90° is (0, 0.2). Camera: (3 + 0, 1 + 0.2) → y = 1.2 m. This rotation then translation is exactly what tf2 computes for you.

Check yourself
  1. Why do the frames of a robot form a tree and not a free network?

    Each frame has exactly one parent, so there is exactly one path between two frames, and one single transform.

  2. What is the difference between the frames odom and map?

    odom → base_link comes from the wheels: smooth but drifting. map → odom comes from the localisation: it corrects the drift.

  3. Which node turns the URDF and the joint angles into frames on tf?

    robot_state_publisher.

7

Simulation and tools: Gazebo, RViz, rosbag

12 min
You will learn

to drive a simulated robot, read its sensors, and record a test to replay it later.

7.1 Simulate first

A simulator replaces the real robot and its world. It publishes the same topics as the real robot (/scan, /odom, /tf) and listens to the same commands (/cmd_vel). Your nodes do not know the difference: you test at your desk, without breaking anything, then move to the real robot.

ToolWhat it does
GazeboSimulates physics, sensors and a 3D world. The standard free simulator with ROS 2.
RVizDisplays the data of the robot, simulated or real (lesson 6).
rosbagRecords topics in a file and replays them later, like a flight recorder.
rqtSmall windows: the node graph, live plots, the list of parameters.
ros2 doctorChecks the installation and the network.

7.2 Drive a simulated robot

The TurtleBot 3 is a small two-wheel robot with a laser scanner, used everywhere for learning. Its simulation is free:

sudo apt install ros-jazzy-turtlebot3-gazebo ros-jazzy-teleop-twist-keyboard
export TURTLEBOT3_MODEL=burger

ros2 launch turtlebot3_gazebo turtlebot3_world.launch.py     # terminal 1: the simulated robot and its world

ros2 run teleop_twist_keyboard teleop_twist_keyboard         # terminal 2: drive it with the keyboard
ros2 topic echo /odom --once                                 # terminal 3: where the robot thinks it is
ros2 topic echo /scan --once                                 #             one turn of the laser scanner
rviz2                                                        # add the displays LaserScan, TF and RobotModel

ros2 bag record -o run1 /scan /odom /tf /cmd_vel             # record a test...
ros2 bag info run1
ros2 bag play run1                                           # ...and replay it later, without the robot
If these packages are not available for your version

The names of the simulation packages change from one distribution to the next. If apt does not find them, follow the TurtleBot 3 manual (emanual.robotis.com) for your distribution: the topics and the commands of this lesson stay the same.

7.3 The three topics of a mobile robot

TopicDirectionContent
/cmd_velyou → robotthe speed you ask: linear.x (m/s) and angular.z (rad/s). The robot converts it into wheel speeds (mobile robot course).
/odomrobot → youwhere the robot thinks it is, by counting wheel turns
/scanrobot → youthe distances measured by the laser, one per angle
Read a laser scan

A scan has angle_min = 0, angle_increment = 0.0175 rad (1°) and 360 values in ranges. The beam number i points at the angle angle_min + i × angle_increment: ranges[0] is straight ahead, ranges[90] is to the left, ranges[180] is behind. A value of inf means “nothing seen”.

7.4 Simulated time

A simulator can run slower or faster than a real clock. It publishes its own time on the topic /clock. Every node that works with a simulation must use it: set the parameter use_sim_time:=true. Forgetting it gives strange tf errors.

Why rosbag is precious

A bug that happens once an hour on the real robot is very hard to study. Record a bag during the tests: when the bug happens, you replay the exact same sensor data at your desk, as many times as you want, and you test your fix on it.

Key terms

  • simulator
  • Gazebo
  • rosbag
  • teleoperation
  • simulated time
  • LaserScan
The essentials
  • The simulator offers the same topics as the real robot: the same nodes work on both.
  • A mobile robot: you send /cmd_vel, it gives /odom and /scan.
  • rosbag records the topics of a test and replays them at your desk.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

A scan starts at angle 0 with a step of 1°. Which index of ranges points to the left (90°)?

Solution

angle = 0 + i × 1° → i = 90.

Level 2 · Intermediate2

Another laser: angle_min = −180°, step 0.5°. Which index points straight ahead (0°)?

Solution

0 = −180 + i × 0.5 → i = 180 / 0.5 = 360. Always compute the index from angle_min and angle_increment: never assume that index 0 is the front.

Level 3 · Professional3

You record /scan (3 kB per message, 10 Hz) for 60 s. Size of the bag for this topic (MB, with 1 MB = 1000 kB)?

Solution

3 × 10 × 60 = 1800 kB = 1.8 MB. Small: record the laser freely. Camera images fill a disk much faster.

Check yourself
  1. Why can the same node drive the simulated robot and the real one?

    Both offer the same topics with the same message types; the node only knows the topics.

  2. Does RViz simulate the robot?

    No. RViz only displays the data that is published. Gazebo simulates.

  3. What is a rosbag used for?

    To record topics during a test and replay them later, to analyse a problem or test a fix without the robot.

8

The big stacks: Nav2, MoveIt 2 and ros2_control

14 min
You will learn

what the main ready-made systems of ROS 2 do, how they fit together, and how to build a map and navigate in it.

You now know the bricks. The strength of ROS 2 is that the hard problems of the other courses are already solved in open-source stacks: sets of nodes that you configure and launch.

StackJobCourse of this site
slam_toolboxBuilds a map from the laser while the robot drives (SLAM).Perception, planning and AI, lesson 4
Nav2Takes a mobile robot from A to B in a map, avoiding obstacles.Perception, planning and AI, lessons 4, 5 and 7
MoveIt 2Plans the motion of an arm without collision: inverse kinematics, path planning, trajectory.Robot modelling; Perception, planning and AI, lesson 6
ros2_controlThe link between the controllers and the motors, in real time.Dynamics and control
micro-ROSPuts a small ROS 2 node on a microcontroller (ESP32, STM32).Robots in the real world, lesson 4

8.1 Nav2: from A to B

  • Localisation (AMCL) compares the laser with the map to find where the robot is: it publishes map → odom.
  • The costmaps are grids that mark the walls and the obstacles seen right now, enlarged by the size of the robot.
  • The global planner finds the whole path in the map; the controller follows it and publishes /cmd_vel 20 times per second.
  • A behaviour tree runs the whole: plan, follow, and if the robot is stuck, clear the map, turn, back up, try again.

Build a map with slam_toolbox, save it, then navigate in it:

sudo apt install ros-jazzy-navigation2 ros-jazzy-nav2-bringup ros-jazzy-slam-toolbox

# 1. build a map: drive the robot around while slam_toolbox draws the map
ros2 launch turtlebot3_gazebo turtlebot3_world.launch.py
ros2 launch slam_toolbox online_async_launch.py use_sim_time:=true
ros2 run teleop_twist_keyboard teleop_twist_keyboard
ros2 run nav2_map_server map_saver_cli -f ~/my_map          # writes my_map.pgm and my_map.yaml

# 2. navigate in this map: click "2D Pose Estimate", then "Nav2 Goal" in RViz
ros2 launch nav2_bringup bringup_launch.py use_sim_time:=true map:=$HOME/my_map.yaml
ros2 launch nav2_bringup rviz_launch.py

8.2 MoveIt 2: move an arm without collision

  1. It reads the URDF of the arm and a description of the obstacles.
  2. You give a target for the tool. MoveIt solves the inverse kinematics.
  3. It plans a path in the joint space that touches nothing (RRT and its cousins).
  4. It turns the path into a trajectory with speeds and accelerations inside the limits.
  5. It sends it to the arm with the action FollowJointTrajectory.

8.3 ros2_control: the last metre before the motors

ros2_control separates two things. A hardware interface talks to the real motors (or to the simulator): it reads positions and writes commands. Controllers are plugged on top: diff_drive_controller turns /cmd_vel into wheel speeds and computes the odometry; joint_trajectory_controller follows the trajectories of MoveIt. To change the robot you only change the hardware interface.

ROS 2 and safety

These stacks are powerful but they are not certified safety systems. A node can crash, a message can be late. The emergency stop, the safety laser scanner and the speed limits of a real robot stay in certified hardware, outside ROS 2 (see the lesson on safety in “Robots in the real world”).

Key terms

  • SLAM
  • Nav2
  • AMCL
  • costmap
  • MoveIt 2
  • ros2_control
  • hardware interface
The essentials
  • slam_toolbox builds the map; Nav2 drives a mobile robot from A to B in it.
  • MoveIt 2 plans the motion of an arm without collision.
  • ros2_control links the controllers to the motors. Safety stays outside ROS 2.
The controller of Nav2 sends linear.x and angular.z: the robot follows a circle of radius r = v / ω.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

/cmd_vel: linear.x = 0.2 m/s, angular.z = 0.5 rad/s. Radius of the circle (m)?

Solution

r = v / ω = 0.2 / 0.5 = 0.4 m.

Level 2 · Intermediate2

The robot turns on the spot at 0.6 rad/s. Time to turn by 90° (s)?

Solution

90° = π/2 = 1.571 rad; 1.571 / 0.6 = 2.62 s.

Level 3 · Professional3

A 6-axis arm must pick a part between two machines without touching them. Which stack?

  1. MoveIt 2
  2. Nav2
  3. slam_toolbox

Solution

Collision-free motion of an arm is the job of MoveIt 2; Nav2 and slam_toolbox are for mobile robots.

Check yourself
  1. In Nav2, which part publishes /cmd_vel?

    The controller (local planner): it follows the global path and avoids the obstacles seen right now.

  2. What does MoveIt 2 need to know about the arm?

    Its URDF (links, joints, limits, shapes for collisions) and how to send it a trajectory.

  3. Why is the emergency stop not a ROS 2 node?

    Safety must not depend on software that can crash or be late: it uses certified hardware that cuts the power.

9

Project: a robot that drives and avoids obstacles

15 min
You will learn

to write a complete node that reads the laser and drives the robot, test it in simulation, and know what to learn next.

9.1 The plan

The robot drives straight ahead. When the laser sees an obstacle closer than 40 cm in front, the robot turns on the spot until the way is free. It is the loop sense → think → act:

9.2 The node

File my_robot/my_robot/safe_driver.py (declare it in setup.py, and add geometry_msgs and sensor_msgs to package.xml). It follows the pattern of lesson 3: the laser callback only stores the nearest distance in front; a 10 Hz timer decides and publishes.

import math

import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan


class SafeDriver(Node):
    """Drive forward, and turn on the spot when an obstacle is closer than stop_distance."""

    def __init__(self):
        super().__init__('safe_driver')
        self.declare_parameter('speed', 0.15)             # m/s
        self.declare_parameter('stop_distance', 0.40)     # m
        self.front = math.inf                             # nearest obstacle in front (m)
        self.cmd = self.create_publisher(Twist, 'cmd_vel', 10)
        self.scan = self.create_subscription(LaserScan, 'scan', self.on_scan, qos_profile_sensor_data)
        self.timer = self.create_timer(0.1, self.control)  # the control loop: 10 Hz

    def on_scan(self, msg):
        # keep the beams within 25 degrees of straight ahead (angle 0)
        near = []
        for i, r in enumerate(msg.ranges):
            angle = msg.angle_min + i * msg.angle_increment
            angle = math.atan2(math.sin(angle), math.cos(angle))      # wrap to [-pi, pi]
            if abs(angle) < math.radians(25) and msg.range_min < r < msg.range_max:
                near.append(r)
        self.front = min(near) if near else math.inf

    def control(self):
        cmd = Twist()
        if self.front > self.get_parameter('stop_distance').value:
            cmd.linear.x = self.get_parameter('speed').value          # the way is free: go
        else:
            cmd.angular.z = 0.6                                       # obstacle: turn left on the spot
        self.cmd.publish(cmd)


def main():
    rclpy.init()
    node = SafeDriver()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.cmd.publish(Twist())                                     # stop the robot before leaving
        node.destroy_node()
        rclpy.try_shutdown()


if __name__ == '__main__':
    main()
  • qos_profile_sensor_data is the best effort QoS of lesson 2: it matches what laser drivers publish.
  • The two parameters let you tune the robot without editing the code.
  • When the node stops, it publishes a zero speed: never leave a robot with its last command.

9.3 Test it

ros2 launch turtlebot3_gazebo turtlebot3_world.launch.py          # terminal 1
ros2 run my_robot safe_driver --ros-args -p use_sim_time:=true    # terminal 2
ros2 param set /safe_driver speed 0.25                            # terminal 3: go faster
ros2 topic echo /cmd_vel                                          #             see the commands
If the robot does not move

Type ros2 topic info /cmd_vel. On recent distributions some robots, the TurtleBot 3 among them, expect the type geometry_msgs/msg/TwistStamped (a Twist with a time stamp) instead of Twist. In that case publish a TwistStamped: fill msg.header.stamp = self.get_clock().now().to_msg() and put the speeds in msg.twist. The two types on the same topic do not connect, and there is no error message.

Make it better
  1. Turn to the side where there is more free space (compare the beams on the left and on the right).
  2. Slow down when the obstacle gets close: speed proportional to the distance (a P controller, like in the control course).
  3. Write a launch file that starts the simulation and your node with a YAML file of parameters.
  4. Record a bag of /scan and /cmd_vel, and replay it to check your logic without the simulator.

9.4 Where to go next

If you want to…LearnOn this site
make a mobile robot navigateNav2, slam_toolbox, robot_localization (Kalman filter)Wheeled mobile robots
control a robot armMoveIt 2, ros2_controlRobot modelling; Dynamics and control
use a cameraimage_transport, cv_bridge with OpenCVPerception, planning and AI
build a real robotmicro-ROS, a URDF of your robot, a hardware interfaceRobots in the real world

The official tutorials on docs.ros.org follow the same order as this course and go further on every point. Do them with the simulator open.

Key terms

  • control loop
  • sensor QoS
  • TwistStamped
  • teleoperation
The essentials
  • Sense → think → act: subscribe to the sensor, decide in a timer, publish the command.
  • Parameters let you tune the node without editing it.
  • Always send a zero speed when the node stops.
Improvement 2 of the project: the robot slows down smoothly instead of stopping at once.

Worked exercises

Do each exercise on paper first, then type your answer (a small error is accepted) or pick an option. Open the hint if you are stuck, then read the solution: every step is explained.

Level 1 · Beginner1

The robot drives at 0.15 m/s. The obstacle is at 1.0 m and the stop distance is 0.40 m. Time before it stops going forward (s)?

Solution

It can travel 1.0 − 0.4 = 0.6 m: 0.6 / 0.15 = 4 s.

Level 2 · Intermediate2

Improved node: speed = 0.5 × (distance − 0.4). Speed when the obstacle is at 0.9 m (m/s)?

Solution

0.5 × (0.9 − 0.4) = 0.5 × 0.5 = 0.25 m/s. The speed falls to zero as the robot reaches 0.4 m.

Level 3 · Professional3

The laser publishes at 10 Hz and the timer runs at 10 Hz. In the worst case the reaction is 0.2 s late. Distance travelled at 0.25 m/s during this delay (cm)?

Solution

0.25 × 0.2 = 0.05 m = 5 cm. The stop distance must include this delay and the braking distance: this is why a fast robot needs a larger stop distance.

Check yourself
  1. Why does the laser callback only store a value instead of driving the robot?

    Callbacks must stay short, and the command must be sent at a regular rate by the timer, even if a scan is late.

  2. Why publish a zero speed when the node stops?

    Otherwise the robot may keep executing the last command it received.

  3. The node publishes Twist but the robot expects TwistStamped. What happens?

    Nothing: the types differ, so the publisher and the subscriber do not connect, and the robot does not move.

Glossary

All the words of the course in one place.

TermMeaning
NodeOne running program that does one job.
TopicA named channel where nodes publish and receive messages.
MessageOne piece of data with a fixed type (fields with names).
ServiceA request and its answer between two nodes.
ActionA long task with a goal, feedback and a result, that can be cancelled.
ParameterA named setting of a node.
QoSQuality of service: how messages are delivered (reliable or best effort, queue size).
PackageA folder with nodes, launch files and description files; the unit that is built and shared.
WorkspaceThe folder that holds your packages and where colcon builds them.
colconThe build tool of ROS 2.
Launch fileA file that starts several nodes with their settings.
NamespaceA prefix added to the names of a node, to separate robots.
tf2The library that keeps the tree of frames and computes the transform between any two of them.
URDFAn XML file that describes the links and joints of a robot.
RVizThe 3D viewer that displays the data of the robot.
GazeboThe simulator: physics, sensors and a 3D world.
rosbagA recording of topics that can be replayed.
Nav2The navigation stack for mobile robots.
MoveIt 2The motion planning stack for arms.
ros2_controlThe layer between controllers and motors.

Sources and references

This course was written from these books, papers, standards and documentation. They are also the best way to go further.

  1. ROS 2 documentation, docs.ros.org (Jazzy Jalisco); Navigation 2, docs.nav2.org; MoveIt 2, moveit.picknik.ai. used for: every command, node and package of the course
  2. S. Macenski, T. Foote, B. Gerkey, C. Lalancette, W. Woodall, “Robot Operating System 2: Design, architecture, and uses in the wild”, Science Robotics, 7(66), 2022. used for: the design of ROS 2
  3. P. Corke, Robot Academy, Queensland University of Technology, robotacademy.net.au (Introduction to robotics masterclass). used for: robot programming in practice

You can now read and write ROS 2!

Install it, redo the project of lesson 9 in the simulator, then pick a stack: Nav2 for a mobile robot, MoveIt 2 for an arm.

Go to the wheeled mobile robots course → Home page