Unit 07 · lesson

Write the First `rclpy` Node

Write the First rclpy Node

Before publisher/subscriber behavior, build the smallest useful node mental model.

Create:

~/ros2_ws/src/robotnix_pubsub/robotnix_pubsub/hello_node.py

with:

import rclpy
from rclpy.node import Node


class HelloNode(Node):
    def __init__(self):
        super().__init__('hello_node')
        self.get_logger().info('ROS 2 node is alive')


def main(args=None):
    rclpy.init(args=args)
    node = HelloNode()
    rclpy.spin_once(node, timeout_sec=0.1)
    node.destroy_node()
    rclpy.shutdown()

Read the lifecycle

rclpy.init

create Node subclass instance

node participates in ROS context

spin/process callbacks briefly

destroy node

rclpy.shutdown

The official publisher/subscriber tutorial uses the same core pattern: initialize rclpy, construct a Node subclass, spin it, then shut down.

Do not run it yet through ros2 run

You still need an installed entry point and a workspace build.

That dependency is the lesson.

Checkpoint

Identify which line determines the node's graph name.