ROS 2 Lyrical lab 04 ยท 90 min
C++ publisher and subscriber
Exchange typed state over a topic and inspect the graph, rate and QoS.
Before you start
- Lab 03 complete
- Basic C++ classes and lambdas
Files you will touch
src/robot_topics/src/joint_publisher.cppsrc/robot_topics/src/joint_monitor.cpp
Step 1
Set up
cd ~/robot_ws/src
ros2 pkg create --build-type ament_cmake --license Apache-2.0 robot_topics --dependencies rclcpp std_msgsStep 2
Create the file
class JointPublisher : public rclcpp::Node {
public:
JointPublisher() : Node("joint_publisher") {
pub_ = create_publisher<std_msgs::msg::Float64>("joint_target", 10);
timer_ = create_wall_timer(std::chrono::milliseconds(100), [this] {
std_msgs::msg::Float64 msg; msg.data = target_;
pub_->publish(msg); target_ += 0.01;
});
}
private:
double target_{0.0};
rclcpp::Publisher<std_msgs::msg::Float64>::SharedPtr pub_;
rclcpp::TimerBase::SharedPtr timer_;
};Step 3
Build, run and inspect
colcon build --packages-select robot_topics --symlink-install
source install/setup.bash
ros2 run robot_topics joint_publisher
# Second terminal:
ros2 topic echo /joint_target
ros2 topic hz /joint_targetProof that it works
- /joint_target has type std_msgs/msg/Float64
- The monitor receives increasing values
- ros2 topic hz reports approximately 10 Hz
Recovery notes
- Source the same overlay in every terminal.
- Use ros2 topic info /joint_target --verbose to compare publisher and subscriber QoS.