#include "ros/ros.h" int main(int argc, char** argv) { ros::init(argc, argv, "listener"); ros::NodeHandle nh; while (ros::ok()) { ros::spinOnce(); // do other processing here } return 0; }
class MyNode { public: MyNode() { sub_ = nh_.subscribe("my_topic", 10, &MyNode::myCallback, this); } void myCallback(const std_msgs::String::ConstPtr& msg) { ROS_INFO("Received message: %s", msg->data.c_str()); } void run() { while (ros::ok()) { ros::spinOnce(); // do other processing here rate_.sleep(); } } private: ros::NodeHandle nh_; ros::Subscriber sub_; ros::Rate rate_{10}; }; int main(int argc, char** argv) { ros::init(argc, argv, "my_node"); MyNode node; node.run(); return 0; }This example creates a custom class called MyNode that includes a Subscriber to listen for messages on the "my_topic" topic. The node will continue to process incoming messages and callbacks at a rate of 10 Hz until it is shut down. Package/Library: roscpp