在ROS
中,如果没有现成的消息类型来描述要去传递的消息,通常我们会使用自定义的消息类型。
在catkin_ws/src/learning_topic
目录下新建一个文件夹msg
,然后在该文件夹内新建文件Person.msg
:
string name
uint8 sex
uint8 age
uint8 unknown = 0
uint8 male = 1
uint8 female = 2
在catkin_ws/src/learning_topic/package.xml
中添加功能包依赖:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
在catkin_ws/src/learning_topic/CMakeLists.txt
中添加编译选项:
find_package(catkin REQUIRED COMPONENTS
geometry_msgs
roscpp
rospy
std_msgs
turtlesim
message_generation # 这是新加的
)
add_message_files(FILES Person.msg)
generate_messages(DEPENDENCIES std_msgs)
catkin_package(
# INCLUDE_DIRS include
# LIBRARIES learning_topic
CATKIN_DEPENDS geometry_msgs roscpp rospy std_msgs turtlesim message_runtime
# DEPENDS system_lib
)
最后编程生成语言相关文件:
$ cd ~/catkin_ws
$ catkin_make
于是会在catkin_ws/devel/include/learning_topic
目录下生成一个Person.h
文件。
在catkin_ws/src/learning_topic/src
下新建文件person_publisher.cpp
:
/* 该例程将发布“/person_info”话题,自定义消息类型“learning_topic::Person” */
#include <ros/ros.h>
#include "learning_topic/Person.h"
int main ( int argc, char **argv ) {
ros::init ( argc, argv, "person_publisher" ); /* ROS节点初始化 */
ros::NodeHandle n; /* 创建节点句柄 */
/* 创建一个Publisher,发布名为“/person_info”的topic,消息类型为“learning_topic::Person”