Bird
Raised Fist0
ROSframework~20 mins

Message timing and frequency in ROS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ROS Timing Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
Understanding ROS Publisher Frequency
In a ROS node, a publisher is set to publish messages at 10 Hz using a rospy.Rate(10). What will happen if the message processing inside the loop takes longer than 0.1 seconds?
ROS
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(10)  # 10hz
    while not rospy.is_shutdown():
        rospy.loginfo('Hello ROS')
        pub.publish('Hello ROS')
        # Simulate long processing
        rospy.sleep(0.15)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass
AThe node will publish messages exactly every 0.1 seconds regardless of processing time.
BThe node will publish messages slower than 10 Hz because processing delays add to the sleep time.
CThe node will publish messages faster than 10 Hz because the sleep time is fixed at 0.1 seconds.
DThe node will throw a runtime error due to conflicting sleep calls.
Attempts:
2 left
💡 Hint
Think about how rospy.Rate.sleep() works when the loop takes longer than the intended rate period.
📝 Syntax
intermediate
1:30remaining
Correct ROS Timer Usage for Periodic Callbacks
Which of the following ROS Python timer initializations correctly calls a function timer_callback every 0.5 seconds?
ROS
def timer_callback(event):
    rospy.loginfo('Timer triggered')
Arospy.Timer(rospy.Duration(0.5), timer_callback())
Brospy.Timer(0.5, timer_callback)
Crospy.Timer(timer_callback, rospy.Duration(0.5))
Drospy.Timer(rospy.Duration(0.5), timer_callback)
Attempts:
2 left
💡 Hint
Check the order and types of arguments required by rospy.Timer.
❓ state_output
advanced
2:00remaining
Effect of Queue Size on Message Delivery Frequency
A ROS subscriber node subscribes to a topic with a queue size of 1. The publisher sends messages at 50 Hz, but the subscriber callback takes 0.05 seconds to process each message. What is the effective message processing frequency at the subscriber?
ROS
import rospy
from std_msgs.msg import String

def callback(msg):
    rospy.sleep(0.05)  # Simulate processing time
    rospy.loginfo('Received message')

rospy.init_node('listener')
rospy.Subscriber('chatter', String, callback, queue_size=1)
rospy.spin()
A10 Hz, because the subscriber callback limits processing to 0.1 seconds per message.
B50 Hz, because the subscriber receives all messages published.
C20 Hz, because the subscriber processes messages slower than the publisher rate and queue size 1 drops older messages.
D0 Hz, because the subscriber cannot keep up and stops receiving messages.
Attempts:
2 left
💡 Hint
Consider how queue size and processing time affect message buffering and delivery.
🔧 Debug
advanced
2:00remaining
Diagnosing Unexpected Message Frequency in ROS Publisher
A ROS publisher node is intended to publish messages at 5 Hz but is observed to publish at 10 Hz. The code snippet is below. What is the cause?
ROS
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(5)  # 5hz
    while not rospy.is_shutdown():
        pub.publish('Hello')
        pub.publish('Hello again')
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass
AThe node publishes twice per loop, effectively doubling the message frequency to 10 Hz.
BThe <code>rospy.Rate</code> is set incorrectly and defaults to 10 Hz.
CThe <code>queue_size</code> of 10 causes messages to be sent faster.
DThe <code>rate.sleep()</code> is called twice, doubling the frequency.
Attempts:
2 left
💡 Hint
Look at how many times pub.publish is called inside the loop.
🧠 Conceptual
expert
3:00remaining
ROS Message Timing with Multiple Timers and Callbacks
Consider a ROS node with two timers: Timer A triggers every 0.2 seconds and Timer B triggers every 0.5 seconds. Both timers execute callbacks that take 0.1 seconds to complete. Assuming the node uses a single-threaded spinner, what is the expected behavior of the callbacks over time?
ROS
import rospy

def callback_a(event):
    rospy.sleep(0.1)
    rospy.loginfo('Timer A callback')

def callback_b(event):
    rospy.sleep(0.1)
    rospy.loginfo('Timer B callback')

rospy.init_node('multi_timer')
timer_a = rospy.Timer(rospy.Duration(0.2), callback_a)
timer_b = rospy.Timer(rospy.Duration(0.5), callback_b)
rospy.spin()
ACallbacks may be delayed because the single-threaded spinner queues callbacks; some callbacks may run later than scheduled.
BThe node will crash due to overlapping callback execution in a single-threaded spinner.
CTimer B's callback will preempt Timer A's callback because it has a longer interval.
DBoth callbacks run exactly at their timer intervals without delay due to ROS internal scheduling.
Attempts:
2 left
💡 Hint
Think about how single-threaded execution affects timer callbacks that take time to complete.

Practice

(1/5)
1. What is the main purpose of using ros::Rate in a ROS node?
easy
A. To initialize the ROS node
B. To store messages received from other nodes
C. To shut down the ROS system safely
D. To control how often the loop runs and messages are sent

Solution

  1. Step 1: Understand the role of ros::Rate

    ros::Rate is used to specify the frequency at which a loop runs in a ROS node.
  2. Step 2: Connect frequency control to message timing

    By controlling loop frequency, ros::Rate indirectly controls how often messages are published or processed.
  3. Final Answer:

    To control how often the loop runs and messages are sent -> Option D
  4. Quick Check:

    Message timing = loop frequency = To control how often the loop runs and messages are sent [OK]
Hint: Remember: ros::Rate sets loop speed for message timing [OK]
Common Mistakes:
  • Confusing ros::Rate with message storage
  • Thinking ros::Rate initializes or shuts down nodes
  • Ignoring its role in timing control
2. Which of the following is the correct way to create a ros::Rate object for 10 Hz frequency?
easy
A. ros::Rate loop_rate = 10;
B. ros::Rate loop_rate(0.1);
C. ros::Rate loop_rate(10);
D. ros::Duration loop_rate(0.1);

Solution

  1. Step 1: Recall ros::Rate constructor syntax

    The constructor takes a double representing frequency in Hz, e.g., ros::Rate(10) for 10 Hz.
  2. Step 2: Check each option for correct syntax

    ros::Rate loop_rate(10); uses correct constructor syntax. ros::Rate loop_rate = 10; assigns int directly, which is invalid. ros::Rate loop_rate(0.1); uses 0.1 Hz, not 10 Hz. ros::Duration loop_rate(0.1); uses wrong class ros::Duration.
  3. Final Answer:

    ros::Rate loop_rate(10); -> Option C
  4. Quick Check:

    Constructor needs frequency in Hz = ros::Rate loop_rate(10); [OK]
Hint: Use ros::Rate(freq) with freq as number in Hz [OK]
Common Mistakes:
  • Using assignment instead of constructor
  • Confusing frequency with period (0.1 instead of 10)
  • Confusing ros::Rate with ros::Duration
3. Given the code snippet:
ros::Rate loop_rate(5);
int count = 0;
while (ros::ok() && count < 3) {
  ROS_INFO("Count: %d", count);
  loop_rate.sleep();
  count++;
}

How many seconds will this loop approximately take to finish?
medium
A. 0.2 seconds
B. 0.6 seconds
C. 0.4 seconds
D. 0.8 seconds

Solution

  1. Step 1: Understand ros::Rate frequency and sleep duration

    ros::Rate(5) means 5 cycles per second, so each cycle lasts 1/5 = 0.2 seconds.
  2. Step 2: Calculate total time for 3 iterations

    3 iterations x 0.2 seconds each = 0.6 seconds. The loop calls sleep() 3 times (once after each print), totaling 0.6 seconds of sleep time. Computation (ROS_INFO, increment) is negligible, so approximately 0.6 seconds.
  3. Final Answer:

    0.6 seconds -> Option B
  4. Quick Check:

    3 x 0.2s = 0.6s [OK]
Hint: Multiply iterations by 1/frequency to get total time [OK]
Common Mistakes:
  • Confusing frequency with period
  • Overestimating computation overhead
  • Counting iterations incorrectly
4. Identify the error in this ROS loop code:
ros::Rate loop_rate(10);
while (ros::ok()) {
  ROS_INFO("Running");
  loop_rate.sleep();
  loop_rate.sleep();
}
medium
A. Calling loop_rate.sleep() twice causes the loop to run at half frequency
B. Missing ros::spinOnce() call inside the loop
C. ros::Rate must be declared inside the loop
D. ROS_INFO cannot be used inside loops

Solution

  1. Step 1: Analyze the effect of calling loop_rate.sleep() twice

    Each call to loop_rate.sleep() pauses the loop to maintain the set frequency. Calling it twice doubles the sleep time, effectively halving the loop frequency.
  2. Step 2: Check other options for correctness

    Missing ros::spinOnce() call inside the loop is not mandatory unless callbacks are used. ros::Rate must be declared inside the loop is incorrect; ros::Rate is usually declared outside the loop. ROS_INFO cannot be used inside loops is false; ROS_INFO is commonly used inside loops.
  3. Final Answer:

    Calling loop_rate.sleep() twice causes the loop to run at half frequency -> Option A
  4. Quick Check:

    Extra sleep doubles wait time = half frequency [OK]
Hint: One sleep call per loop to keep correct frequency [OK]
Common Mistakes:
  • Calling sleep multiple times per loop
  • Thinking ros::Rate must be inside loop
  • Assuming ROS_INFO is invalid in loops
5. You want a ROS node to publish sensor data at 20 Hz but only if new data is available. Which approach best controls message timing and frequency?
hard
A. Use ros::Rate(20) and call loop_rate.sleep() every loop, publishing only when data is new
B. Publish data immediately when available without any rate control
C. Use ros::Rate(1) and publish data every second regardless of availability
D. Call loop_rate.sleep() twice per loop to slow down publishing

Solution

  1. Step 1: Understand the requirement for 20 Hz publishing only when data is new

    The node should run at 20 Hz frequency but publish messages conditionally based on data availability.
  2. Step 2: Evaluate each option for meeting this requirement

    Use ros::Rate(20) and call loop_rate.sleep() every loop, publishing only when data is new correctly sets loop frequency to 20 Hz and publishes only when new data exists. Publish data immediately when available without any rate control lacks frequency control, risking irregular timing. Use ros::Rate(1) and publish data every second regardless of availability sets too low frequency (1 Hz). Call loop_rate.sleep() twice per loop to slow down publishing slows down publishing incorrectly by double sleeping.
  3. Final Answer:

    Use ros::Rate(20) and call loop_rate.sleep() every loop, publishing only when data is new -> Option A
  4. Quick Check:

    Set rate high, publish conditionally = Use ros::Rate(20) and call loop_rate.sleep() every loop, publishing only when data is new [OK]
Hint: Set high rate, publish only when needed inside loop [OK]
Common Mistakes:
  • Ignoring rate control causing irregular timing
  • Using too low frequency for sensor data
  • Calling sleep multiple times to slow down
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