Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a ROS publisher that publishes messages at a fixed rate.
ROS
ros::Rate loop_rate([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name instead of a number for the rate.
Confusing ros::Rate with ros::spin.
✗ Incorrect
The ros::Rate object controls the frequency of the loop. Here, 10 means 10 Hz, so the loop runs 10 times per second.
2fill in blank
mediumComplete the code to publish a message and maintain the loop rate.
ROS
while (ros::ok()) { pub.publish(msg); ros::spinOnce(); [1].sleep(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Calling ros::sleep() instead of loop_rate.sleep().
Forgetting to call sleep(), causing the loop to run too fast.
✗ Incorrect
The loop_rate.sleep() call pauses the loop to maintain the desired frequency.
3fill in blank
hardFix the error in the code to correctly set the message publishing frequency.
ROS
ros::Rate loop_rate([1]); while (ros::ok()) { pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using zero or negative numbers for frequency.
Passing the frequency as a string instead of a number.
✗ Incorrect
The frequency must be a positive number. Using 10 sets the loop to run at 10 Hz. Zero or negative values cause errors. Passing a string is invalid.
4fill in blank
hardFill both blanks to create a ROS timer that calls a callback function at a fixed rate.
ROS
ros::Timer timer = nh.createTimer(ros::Duration([1]), [2]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using ros::spin instead of a callback function.
Passing the timer period as an integer instead of a float.
✗ Incorrect
The ros::Duration argument sets the timer period in seconds (0.5 means every half second). The callback function is passed as the second argument.
5fill in blank
hardFill all three blanks to create a ROS node that publishes messages at 5 Hz using a timer.
ROS
ros::NodeHandle nh; ros::Publisher pub = nh.advertise<std_msgs::String>("chatter", 1000); ros::Timer timer = nh.createTimer(ros::Duration([1]), [2]); void [3](const ros::TimerEvent&) { std_msgs::String msg; msg.data = "Hello"; pub.publish(msg); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong timer period for 5 Hz.
Mismatching the callback function name.
✗ Incorrect
0.2 seconds means the timer triggers 5 times per second (5 Hz). The callback function name must match the function defined, here 'timerCallback'.
