Bird
Raised Fist0
ROSframework~20 mins

Creating a publisher node in ROS - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ROS 2 Publisher Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this ROS publisher node?
Consider this ROS 2 Python publisher node code snippet. What will be printed on the console when the node runs?
ROS
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class MinimalPublisher(Node):
    def __init__(self):
        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(String, 'topic', 10)
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0

    def timer_callback(self):
        msg = String()
        msg.data = f'Hello, world: {self.i}'
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: {msg.data}')
        self.i += 1


def main(args=None):
    rclpy.init(args=args)
    minimal_publisher = MinimalPublisher()
    rclpy.spin(minimal_publisher)
    minimal_publisher.destroy_node()
    rclpy.shutdown()
AThe node prints 'Publishing: Hello, world: 0' every 0.5 seconds, incrementing the number each time.
BThe node prints 'Hello, world' once and then stops.
CThe node does not print anything because the timer is not started.
DThe node prints 'Publishing: Hello, world: 0' once and then crashes with an error.
Attempts:
2 left
💡 Hint
Look at the timer callback and how often it triggers.
📝 Syntax
intermediate
2:00remaining
Which option contains a runtime error in creating a ROS 2 publisher node?
Identify the code snippet that will cause a runtime error when defining a ROS 2 publisher node in Python.
Aself.publisher_ = self.create_publisher(String, 'topic', 10)
Bself.publisher_ = self.create_publisher(String, topic, 10)
C
def timer_callback(self):
    msg = String()
    msg.data = f'Hello {self.i}'
    self.publisher_.publish(msg)
    self.get_logger().info(f'Publishing: {msg.data}')
    self.i += 1
Dself.timer = self.create_timer(0.5, self.timer_callback)
Attempts:
2 left
💡 Hint
Check if the topic name is a string literal.
❓ state_output
advanced
1:30remaining
What is the value of 'i' after 5 timer callbacks in this ROS 2 publisher node?
Given the following snippet inside a ROS 2 publisher node, what is the value of self.i after the timer callback has run 5 times?
ROS
def __init__(self):
    super().__init__('minimal_publisher')
    self.i = 0

def timer_callback(self):
    self.i += 1
A5
B4
C6
D0
Attempts:
2 left
💡 Hint
The counter starts at zero and increments by one each callback.
🔧 Debug
advanced
2:00remaining
Which option causes a runtime error when running this ROS 2 publisher node?
Identify the code snippet that will cause a runtime error when the node runs.
ROS
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class MinimalPublisher(Node):
    def __init__(self):
        super().__init__('minimal_publisher')
        self.publisher_ = self.create_publisher(String, 'topic', 10)
        self.timer = self.create_timer(0.5, self.timer_callback)
        self.i = 0
        self.extra_method()

    def timer_callback(self):
        msg = String()
        msg.data = f'Hello {self.i}'
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: {msg.data}')
        self.i += 1

    def extra_method(self):
        print(self.undefined_variable)
AThe node runs without any errors.
BThe timer callback causes a TypeError because msg.data is not a string.
CThe publisher creation causes a SyntaxError due to wrong arguments.
DCalling extra_method() causes AttributeError because undefined_variable does not exist.
Attempts:
2 left
💡 Hint
Look for undefined variables accessed in methods.
🧠 Conceptual
expert
2:30remaining
Which option best describes the role of QoS profile in ROS 2 publisher creation?
In ROS 2, when creating a publisher with create_publisher(), what does the QoS profile argument control?
AIt defines the callback function to be called when a message is published.
BIt sets the topic name and message type for the publisher.
CIt controls how messages are delivered, including reliability, durability, and history settings.
DIt specifies the frequency at which messages are published.
Attempts:
2 left
💡 Hint
Think about message delivery guarantees and behavior.

Practice

(1/5)
1. What is the main purpose of a publisher node in ROS?
easy
A. To store data in a database
B. To receive messages from other nodes
C. To compile the ROS package
D. To send messages on a topic to share information

Solution

  1. Step 1: Understand the role of a publisher node

    A publisher node sends messages to other nodes by publishing on a topic.
  2. Step 2: Compare options with the role

    Only To send messages on a topic to share information describes sending messages on a topic, which matches the publisher's role.
  3. Final Answer:

    To send messages on a topic to share information -> Option D
  4. Quick Check:

    Publisher node = sends messages [OK]
Hint: Publisher nodes send messages, subscribers receive them [OK]
Common Mistakes:
  • Confusing publisher with subscriber
  • Thinking publisher stores data
  • Assuming publisher compiles code
2. Which of the following is the correct way to create a publisher in a ROS2 Python node?
easy
A. self.createPublisher(String, 'topic_name', 10)
B. self.create_publisher(String, 'topic_name', 10)
C. create_publisher(String, 'topic_name', 10)
D. self.create_publisher('topic_name', String, 10)

Solution

  1. Step 1: Recall ROS2 Python publisher syntax

    The method is called on the node instance as self.create_publisher, with message type first, then topic name, then queue size.
  2. Step 2: Check each option's syntax

    self.create_publisher(String, 'topic_name', 10) matches the correct method name and argument order. self.createPublisher(String, 'topic_name', 10) has wrong method name casing. create_publisher(String, 'topic_name', 10) misses self. self.create_publisher('topic_name', String, 10) swaps argument order.
  3. Final Answer:

    self.create_publisher(String, 'topic_name', 10) -> Option B
  4. Quick Check:

    Correct method and argument order = self.create_publisher(String, 'topic_name', 10) [OK]
Hint: Use self.create_publisher with message type first [OK]
Common Mistakes:
  • Wrong method name casing
  • Missing self when calling method
  • Swapping topic name and message type
3. Given this ROS2 Python publisher code snippet, what will be printed when the timer callback runs?
def timer_callback(self):
    msg = String()
    msg.data = 'Hello ROS'
    self.publisher.publish(msg)
    print('Published:', msg.data)
medium
A. Published: Hello ROS
B. Hello ROS
C. Published: msg.data
D. Error: msg.data undefined

Solution

  1. Step 1: Analyze the print statement

    The print outputs the string 'Published:' followed by the value of msg.data, which is 'Hello ROS'.
  2. Step 2: Confirm msg.data value

    msg.data is assigned 'Hello ROS' before publishing, so the print shows 'Published: Hello ROS'.
  3. Final Answer:

    Published: Hello ROS -> Option A
  4. Quick Check:

    Print shows 'Published:' plus msg.data [OK]
Hint: Print uses string plus msg.data value [OK]
Common Mistakes:
  • Printing variable name instead of value
  • Assuming print shows only msg.data
  • Confusing msg.data with undefined
4. Identify the error in this ROS2 Python publisher node snippet:
def __init__(self):
    self.publisher = self.create_publisher(String, 'chatter', 10)

def timer_callback(self):
    msg = String()
    msg.data = 'Hello'
    self.publisher.publish(msg)

self.timer = self.create_timer(1.0, timer_callback)
medium
A. timer_callback is missing 'self' parameter
B. create_publisher is called with wrong arguments
C. Timer is created outside the class constructor
D. msg.data is assigned incorrectly

Solution

  1. Step 1: Check code structure and indentation

    The self.timer = self.create_timer(1.0, timer_callback) line lacks indentation and appears outside __init__ at class level, where 'self' is undefined, causing NameError.
  2. Step 2: Verify other options

    A: timer_callback includes 'self'. B: create_publisher args are correct (type, topic, qos). D: msg.data = 'Hello' is valid.
  3. Final Answer:

    Timer is created outside the class constructor -> Option C
  4. Quick Check:

    self assignments must be inside instance methods like __init__ [OK]
Hint: Create timers inside __init__ with self.create_timer(1.0, self.timer_callback) [OK]
Common Mistakes:
  • Omitting 'self' in method parameters
  • Misordering create_publisher arguments
  • Creating timer outside class context
5. You want to create a ROS2 publisher node that publishes integers incrementing every second starting from 0. Which code snippet correctly implements this behavior?
hard
A. class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 0 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = self.i self.publisher.publish(msg) self.i += 1
B. class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 0 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(): msg = Int32() msg.data = self.i self.publisher.publish(msg) self.i += 1
C. class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 0 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = 0 self.publisher.publish(msg) self.i += 1
D. class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 1 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = self.i self.publisher.publish(msg) self.i = 0

Solution

  1. Step 1: Check timer_callback method signatures

    Options A and C define timer_callback(self); B omits 'self', causing AttributeError on self.i and self.publisher.
  2. Step 2: Verify increment logic

    class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 0 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = self.i self.publisher.publish(msg) self.i += 1 initializes self.i=0 and does self.i += 1 after publishing, yielding 0,1,2,... class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 0 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = 0 self.publisher.publish(msg) self.i += 1 always publishes 0. class IntPublisher(Node): def __init__(self): super().__init__('int_publisher') self.publisher = self.create_publisher(Int32, 'numbers', 10) self.i = 1 self.timer = self.create_timer(1.0, self.timer_callback) def timer_callback(self): msg = Int32() msg.data = self.i self.publisher.publish(msg) self.i = 0 publishes 1 then sets self.i=0 repeatedly.
  3. Final Answer:

    self.i = 0; msg.data = self.i; self.i += 1 -> Option A
  4. Quick Check:

    self.i starts 0, increment after publish [OK]
Hint: Use self.i and increment after publishing in timer callback [OK]
Common Mistakes:
  • Missing 'self' in timer_callback
  • Not incrementing the counter
  • Resetting counter inside callback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard