套路总结:
1.初始化并命名节点;
2.创建句柄;
3.发布消息或订阅消息,topic名称要对应;
4.循环。
talker.cpp↓
#include <ros/ros.h>
#include <topic_demo/gps.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");//初始化并命名节点
ros::NodeHandle nh; //创建句柄,实例化node
topic_demo::gps msg;// 创建GPS消息
msg.x = 1.0;
msg.y = 1.0;
msg.state = "working";
ros::Publisher pub = nh.advertise<topic_demo::gps>("gps_info", 1);//创建publisher,<...>里是要发布的消息的模板类型,"..."是topic的名称,1是待处理队列的长度
ros::Rate loop_rate(1.0);//定义循环发布的频率1Hz
while(ros::ok()){
msg.x = 1.01 * msg.x;
msg.y = 1.02 * msg.y;
ROS_INFO("Talker: GPS: x = %f, y = %f", msg.x, msg.y);//ROS_INFO相当于cout和printf
pub.publish(msg);//发布消息
loop_rate.sleep();//根据定义的频率休眠1s
};
return 0;
}
listener.cpp
#include <ros/ros.h>
#include <topic_demo/gps.h>
#include <std_msgs/Float32.h>
void gpsCallback(const topic_demo::gps::ConstPtr &msg)
{
std_msgs::Float32 distance;//distance是一个结构体,包含了data
distance.data = sqrt(pow(msg->x, 2), pow(msg->y, 2));
ROS_INFO("Listener: Distance to origin = %f, state = %s", distance.data, msg->state.c_str());//c_str()输出字符串的首地址,string s = "123"; printf("%s", s.c_str());输出"123"
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("gps_info", 1, gpsCallback);//"gps_info"为订阅的topic名称,与talker.cpp中发布的topic名称对应
ros::spin();//反复调用当前可触发的回调函数,阻塞
return 0;
}
gps.msg↓
float32 x
float32 y
string state