By Kevin McAleer, 4 Minutes
Page last updated November 24, 2026

By the end of this lesson you will be able to write a ROS 2 node as a Python class and use a timer to run code at a steady rate.
Our first node was a short script. Real nodes need to remember things (a counter, the last sensor reading) and react to events (a timer firing, a message arriving). A class is a natural fit: the node’s memory lives in self, and each event is a method. Almost every ROS 2 Python node you’ll meet is written this way.
Save this as counter.py in the src folder of your first_app workspace, next to talker.py.
import rclpy
from rclpy.node import Node
class Counter(Node):
def __init__(self):
super().__init__("counter_node")
self.counter_ = 0
self.get_logger().info("Hello World")
self.create_timer(0.5, self.timer_callback)
def timer_callback(self):
self.counter_ += 1
self.get_logger().info("Hello " + str(self.counter_))
def main(args=None):
rclpy.init(args=args)
node = Counter()
rclpy.spin(node)
rclpy.shutdown()
if __name__ == "__main__":
main()
Run it from the container with python3 src/counter.py. You’ll see Hello World once, then Hello 1, Hello 2, Hello 3… twice a second until you press CTRL + C.
sequenceDiagram
participant S as rclpy.spin
participant T as Timer (0.5 s)
participant N as Counter node
S->>T: wait
T->>N: timer_callback()
N->>N: counter_ += 1, log message
S->>T: wait again
class Counter(Node) makes our own node by building on (inheriting from) ROS’s Node class.super().__init__("counter_node") runs the parent’s setup and gives the node its name.self.counter_ = 0 is the node’s memory: a number that survives between calls.self.create_timer(0.5, self.timer_callback) asks ROS to call timer_callback every 0.5 seconds. We hand over the method without brackets; ROS calls it for us.rclpy.spin(node) is what lets the timer fire. Without it the program would start, set things up and exit.Why this matters: a robot’s control loop is just a timer calling a method at a steady rate: read sensors, decide, drive the motors. This is the pattern you’ll reuse for every node.
0.5 to 2.0. How does the output change?self.counter_ % 2).rclpy.shutdown() in the callback. What happens?self.timer_callback (no brackets) and call rclpy.spin(node).Why: Timers only run while the node is spinning, and adding brackets calls the method once instead of scheduling it.
AttributeError mentioning counter_.self.counter_ = 0 is set in __init__, and that you wrote self. each time you use it.self., Python treats it as a different, temporary variable.Quick quiz 1 of 3
What is a ROS node?
Quick quiz 2 of 3
What does self.create_timer(0.5, self.timer_callback) do?
Quick quiz 3 of 3
Where does the node keep a value such as the counter between callbacks?
Comments