Creating ROS nodes

The first node we are going to discuss is demo_topic_publisher.cpp. This node will publish an integer value on a topic called /numbers. Copy the current code into a new package or use this existing file from the code repository.

Here is the complete code:

#include "ros/ros.h" #include "std_msgs/Int32.h" #include <iostream> int main(int argc, char **argv) { ros::init(argc, argv,"demo_topic_publisher"); ros::NodeHandle node_obj; ros::Publisher number_publisher = node_obj.advertise<std_msgs::Int32>("/numbers",10); ros::Rate loop_rate(10); int number_count = 0; while (ros::ok()) { std_msgs::Int32 msg; msg.data = number_count; ROS_INFO("%d",msg.data); number_publisher.publish(msg); ros::spinOnce(); loop_rate.sleep(); ++number_count; ...

Get Mastering ROS for Robotics Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.