1.定义msg文件 功能包下新建 msg 目录,添加文件 Person.msg 文件内容
string name
uint16 age
float64 height
2.编辑配置文件 package.xml中添加编译依赖与执行依赖 <build_depend>message_generation</build_depend> <exec_depend>message_runtime</exec_depend> CMakeLists.txt编辑 msg 相关配置
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)
# 需要加入 message_generation,必须有 std_msgs
## 配置 msg 源文件
add_message_files(
FILES
Person.msg
)
# 生成消息时依赖于 std_msgs
generate_messages(
DEPENDENCIES
std_msgs
)
#执行时依赖
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES demo02_talker_listener
CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
# DEPENDS system_lib
)
add_executable(pub_node src/persion_msg_pub_node.cpp)
add_executable(sub_node src/persion_msg_sub_node.cpp)
#让自定义消息优先编译生成对应头文件,这样在使用的时候防止显示未定义
add_dependencies(pub_node ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(sub_node ${PROJECT_NAME}_generate_messages_cpp)
target_link_libraries(pub_node
${catkin_LIBRARIES}
)
target_link_libraries(sub_node
${catkin_LIBRARIES}
)
pub_node.cpp
#include "ros/ros.h"
#include "persion_msg/Persion.h"
int main(int argc, char *argv[])
{
ros::init(argc, argv, "demo4");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<persion_msg::Persion>("pub_persion_msg",10);
persion_msg::Persion persion;
persion.age = 30;
persion.name = "songjian";
persion.height = 170;
ros::Rate rate(20);
while (ros::ok())
{
pub.publish(persion);
rate.sleep();
ros::spinOnce();
}
return 0;
}
sub_node.cpp
#include "ros/ros.h"
#include "persion_msg/Persion.h"
void Dopersion(const persion_msg::Persion::ConstPtr & msg){
ROS_INFO("name: %s age:%d height:%.2f", msg->name.c_str(), msg->age, msg->height);
}
int main(int argc, char *argv[])
{
ros::init(argc, argv, "demo4_sub");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("pub_persion_msg", 10, Dopersion);
ros::spin();
return 0;
}
|