1.创个话题源码包topic_demo
$ cd ~/catkin_ws/src
$ catkin_create_pkg topic_demo roscpp rospy std_msgs
2.在包下新建msg文件夹自定义消息文件gps.msg
$ cd topic_demo/
$ mkdir msg
$ cd msg
$ vi gps.msg
gps.msg
float32 x
float32 y
string state
3.编写talker.cpp作为publisher节点
#include <ros/ros.h>
#include <topic_demo/gps.h>//自定义msg产生的头文件
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_demo::gps,往"gps_info"话题上发布消息,发送队列长度为1
ros::Rate loop_rate(1.0); //定义循环发布的频率1Hz,一秒钟变化一次,一秒钟发布一次
while(ros::ok){
//只要ros还没关闭就循环
msg.x =