ros中,定义消息是语言无关的,定义消息文件保存在如下
catkin_ws/src/learning_topic/msg/Person.msg
Person.msg 文件就是我们的消息文件,后缀为msg,语言无关,内容如下
//字符串 名称
string name
//uint8 性别
uint8 sex
// uint8 年龄
uint8 age
//这种方式定义性别枚举
uint8 unknown = 0
uint8 male = 1
uint8 female = 2
<build_depend>message_generationbuild_depend>
<exec_depend>message_runtimeexec_depend>
在 find_package 语句后面追加 message_generation
find_package(catkin REQUIRED COMPONENTS
....
message_generation
)
在 add_message_files 后面追加 Person.msg
add_message_files(
FILES
Person.msg
)
在 generate_messages 后面追加 std_msgs
generate_messages(
DEPENDENCIES
std_msgs
)
在 catkin_package后面追加 message_runtime
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/src/learning_topic/src/person_publisher.cpp
内容如下
#include
#include "learning_topic/Person.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "person_publisher");
ros::NodeHandle node;
// 创建一个publisher 发布名为/person_info的主题,消息类型为learning_topic::Person, 队列长度为10
ros::Publisher person_info_pub = node.advertise<learning_topic::Person>("/person_info", 10);
ros::Rate loop_rate(1);
int count = 0;
while (ros::ok())
{
learning_topic::Person person_msg;
person_msg.name = "Tom";
person_msg.age = 18;
person_msg.sex = learning_topic::Person::male;
// 发布消息
person_info_pub.publish(person_msg);
ROS_INFO("Publish Person info: name: %s age: %d, sex: %d", person_msg.name.c_str(), person_msg.age, person_msg.sex);
loop_rate.sleep();
}
return 0;
}
catkin_ws/src/learning_topic/src/person_subscriber.cpp
#include
#include "learning_topic/Person.h"
void person_info_callback(const learning_topic::Person::ConstPtr &msg)
{
ROS_INFO("Subcribe Person info: name: %s age: %d, sex: %d", msg->name.c_str(), msg->age, msg->sex);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "person_subscriber");
ros::NodeHandle node;
ros::Subscriber person_info_sub = node.subscribe("/person_info", 10, person_info_callback);
ros::spin();
return 0;
}
catkin_ws/src/learning_topic/CMakeLists.txt
添加
add_executable(person_publisher src/person_publisher.cpp)
add_executable(person_subscriber src/person_subscriber.cpp)
add_dependencies(person_publisher ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(person_subscriber ${PROJECT_NAME}_generate_messages_cpp)
target_link_libraries(person_publisher
${catkin_LIBRARIES}
)
target_link_libraries(person_subscriber
${catkin_LIBRARIES}
)
cd catkin_ws
catkin_make
roscore
另开一个终端
source devel/setup.sh
rosrun learning_topic person_publisher
source devel/setup.sh
rosrun learning_topic person_subscriber