Education › Robotics › Stage 3: Make it think

ROS 2: the robot operating system

Why a robotics middleware, nodes and topics, and running your first ROS 2 graph.

Intermediate ~35 min read Module 11 of 16

ROS 2 — the Robot Operating System — is the framework nearly every serious robot uses to organise its software. It is not an operating system; it is a way to split a robot's brain into small programs that talk to each other over a common bus. This lesson explains the handful of concepts that unlock ROS 2: nodes, topics, messages, services and the tools to inspect a running system. You do not need ROS to blink an LED, but the moment your robot has several sensors, a planner and motors all running at once, ROS is what keeps it sane.

After this module you can
  • Explain what ROS 2 is and why robots use it
  • Describe nodes, topics, and the publish/subscribe model
  • Tell topics apart from services and know when to use each
  • Use the core command-line tools to inspect a running ROS 2 system

Why a robot needs a framework

A real robot runs many things at once: a camera driver, a lidar driver, a program that finds obstacles, one that plans a path, one that drives the motors, maybe a battery monitor. Cram all of that into one giant program and it becomes impossible to test, reuse, or debug — change the camera and you risk breaking the motors. ROS 2 solves this by letting you write each piece as a small, independent program and giving them a standard way to pass data to each other. The payoff is huge: you can develop and test each part alone, swap one out without touching the others, reuse drivers other people wrote, and run the pieces across several computers. That modularity is why ROS 2 is the near-universal choice for non-trivial robots, in research and increasingly in industry.

Nodes and topics

The two core ideas are nodes and topics. A node is one small program doing one job — a camera node, a motor node, an obstacle-detector node. Nodes do not call each other directly; instead they communicate through topics, which are named channels carrying a stream of messages. A node publishes to a topic (the camera node publishes images to /camera/image) and any number of other nodes subscribe to receive them. This is the publish/subscribe model: publishers and subscribers do not know about each other, they only share the topic name and message type. Add a second node that also wants camera images and it just subscribes to the same topic — nothing else changes. This loose coupling is what makes ROS systems so easy to extend.

Note

The mental model: nodes are the workers, topics are the conveyor belts between them, and messages are the items on the belt. A publisher drops items on a belt; every subscriber to that belt picks them up. No worker needs to know who else is listening.

A publisher and a subscriber

ROS 2 nodes are usually written in Python (with rclpy) or C++. Here is the shape of a Python node that publishes a number every half-second, and a second one that subscribes and prints it. You do not need to memorise the API — notice the structure: create a node, make a publisher or subscription bound to a topic name and message type, and let ROS spin the node so callbacks fire.

python
import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32

class Talker(Node):
    def __init__(self):
        super().__init__('talker')
        self.pub = self.create_publisher(Int32, 'count', 10)
        self.n = 0
        self.create_timer(0.5, self.tick)   # call tick() every 0.5s

    def tick(self):
        msg = Int32()
        msg.data = self.n
        self.pub.publish(msg)               # send it on the 'count' topic
        self.n += 1

def main():
    rclpy.init()
    rclpy.spin(Talker())                    # process callbacks forever
    rclpy.shutdown()

Topics vs services vs actions

Topics are for continuous streams, but not every interaction is a stream. ROS 2 gives you three patterns, and choosing the right one matters. A topic is a one-way stream of data with no reply — sensor readings, motor commands, anything published continuously. A service is a request/response call — you ask a question and wait for one answer, like 'reset the odometry' or 'what is the current map'; use it for quick, occasional commands that need a reply. An action is for long-running goals that report progress and can be cancelled — 'navigate to this room', which takes seconds and streams feedback along the way. The rule of thumb: streaming data → topic; quick call-and-answer → service; a goal that takes time and you want progress on → action.

  • Topic → continuous one-way stream (sensor data, velocity commands).
  • Service → request/response, quick and occasional (reset, query a value).
  • Action → long-running goal with progress and cancellation (navigate somewhere).

Seeing inside a running system

A great strength of ROS 2 is that you can inspect a live robot from the command line without changing any code. The ros2 tool lets you list what is running and even inject or watch data. This is how you debug: is the camera node actually publishing? Echo its topic. Is the motor node receiving commands? Check the topic's subscribers. These commands turn a mysterious 'the robot isn't moving' into a quick diagnosis of exactly which link in the chain is broken.

bash
ros2 node list                 # every node currently running
ros2 topic list                # every active topic
ros2 topic echo /count         # print messages arriving on a topic
ros2 topic hz /camera/image    # measure a topic's publish rate
ros2 topic info /count         # see a topic's type and how many pubs/subs
ros2 service list              # every available service
Hands-on practice

Run your first ROS 2 graph

  1. Install ROS 2 Humble (or run it in the provided Docker image) and source the setup file.
  2. Run the built-in demo talker and listener nodes in two terminals and watch them communicate.
  3. In a third terminal, run 'ros2 topic list' and find the topic the talker publishes on.
  4. Run 'ros2 topic echo' on that topic and confirm you see the same messages the listener prints.
  5. Run 'ros2 topic hz' on the topic to measure how many messages per second it carries.
Cheat sheet

ROS 2: the robot operating system — at a glance

Main things to focus on

  • ROS 2 splits a robot's software into small programs (nodes) that share data.
  • Nodes communicate over named topics using the publish/subscribe model.
  • Publishers and subscribers know only the topic name and message type, not each other.
  • Topic = stream; service = request/response; action = long goal with progress.
  • rclpy (Python) and rclcpp (C++) are the client libraries for writing nodes.
  • The ros2 command-line tools inspect a live system without changing code.

Core concepts

nodeone small program doing one job
topicnamed channel carrying a message stream
messagea typed data item on a topic
publish / subscribesend to / receive from a topic

Communication patterns

topicone-way continuous stream, no reply
servicerequest/response, quick and occasional
actionlong goal with feedback and cancel
rclpy / rclcppPython / C++ node libraries

Writing a node

rclpy.init()start the ROS client library
create_publisher(type, name, q)make a publisher on a topic
create_subscription(...)receive messages via a callback
rclpy.spin(node)process callbacks until shutdown

Inspecting live

ros2 node listrunning nodes
ros2 topic listactive topics
ros2 topic echo <t>print a topic's messages
ros2 topic hz <t>measure publish rate

Common pitfalls

  • Writing one giant program instead of small nodes, losing all the modularity ROS gives.
  • Using a topic for a request that needs an answer — that is what a service is for.
  • Publishing and subscribing with mismatched message types, so nothing is received.
  • Forgetting to spin the node, so callbacks never fire and it looks dead.
  • Debugging blind instead of using ros2 topic echo to see what is actually flowing.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →