1.首先在工作空间下创建 msg 目录用来存储 person.msg 文件
string name
int16 age
float64 heihght
2.修改 package.xml 和 CMakeLists.txt 文件:
在package.xml 文件中修改:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
在 CMakeLists.txt 文件中修改:
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation //在此处添加message_generation
)
## Generate messages in the 'msg' folder 同时,放开下方add_message_files函数的注释
add_message_files(
FILES
Person.msg //在此处添加创建的msg文件名
)
## Generate added messages and services with any dependencies listed here //同样放开此处的注释
generate_messages(
DEPENDENCIES
std_msgs
)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES ros_pub_sub
CATKIN_DEPENDS roscpp rospy std_msgs message_runtime//放开该句的注释,同时在末尾添加 message_runtime
# DEPENDS system_lib
)
3.修改 工作空间/.vscode/c_cpp_properties.json 文件
在 "includePath" 中添加msg文件的绝对路径
发布方实现:
#include "ros/ros.h"
#include "ros_pub_sub/Person.h"
int main(int argc ,char* argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"talker");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<ros_pub_sub::Person>("chatter",10);
ros_pub_sub::Person person;
person.name = "luckye";
person.age = 1;
person.height = 1.73;
ros::Rate r(1);
while(ros::ok())
{
pub.publish(person);
ROS_INFO("发送的内容为: 姓名:%s ,年龄为:%d ,身高为:%.2f ",person.name.c_str(),person.age,person.height);
person.age += 1;
r.sleep();
ros::spinOnce();
}
return 0;
}
订阅方实现:
#include "ros/ros.h"
#include "ros_pub_sub/Person.h"
void doPerson(const ros_pub_sub::Person::ConstPtr &person)
{
ROS_INFO("接收到的内容为:姓名:%s ,年龄:%d ,身高:%.2f",person->name.c_str(),person->age,person->height);
}
int main(int argc , char* argv[])
{
setlocale(LC_ALL,"");
ros::init(argc,argv,"listener");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("chatter",10,doPerson);
ros::spin();
}
修改 CMakeLists.txt 文件编译运行发布方和订阅方 cpp文件
在终端运行情况如下: