ROS (four) --- custom message .msg

First, the project structure

 

 

 New ros package book

Second, the definition msg

 

 

After compilation, the workspace under devel header files include book / Student.h

 

Posted end

#include "ros/ros.h"
#include "book/Student.h"
#include <cstdlib>

using namespace std;
int main(int argc, char** argv)
{
    // Initial and name the Node 
    ROS :: the init (argc, argv, " node_MyMsgPub " ); // initialize node name 
    IF (! Argc = 4 )
    {
        cout<<"Error command parameter!\n"<<"please run command eg:\n"<<"rosrun book_message Book_MyMsgPub LiLei 180 160"<<endl;
        return 1;
    }

    //create mode handle
    ros::NodeHandle nh;  // ros node handle 句柄
    ros::Publisher myMsgPub = nh.advertise<book::Student>("MyMsg",100);  //发布器
    book::Student stdMsg;
    stdMsg.name = argv[1];
    stdMsg.height = atof(argv[2]);
    stdMsg.weight = atof(argv[3]);

    ros::Rate rate(10);
    while(ros::ok)
    {
        myMsgPub.publish(stdMsg);
        rate.sleep();
    }
    return 0;
}

Receive port

#include "ros/ros.h"
#include "book/Student.h"

void MyMsgCallback(const book::Student &stdInfo)
{
    ROS_INFO("student message: \n name:%s---height:%f---weight:%f\n",stdInfo.name.c_str(),stdInfo.height
    ,stdInfo.weight);
}

int main(int argc, char ** argv)
{
    // initial and name node
    ros::init(argc, argv, "node_MyMsgSub");
    
    ros::NodeHandle nh;
    // create subscriber
    ros::Subscriber MyMsgSub = nh.subscribe("MyMsg",1000,&MyMsgCallback);
    ros::spin();
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/feihu-h/p/12417683.html