一、新建项目
# 创建工作空间
mkdir -p demo3/src# 创建功能包
catkin_create_pkg demo roscpp rosmsg message_generation# 打开功能包
cd src/demo
二、创建自定义消息
# 创建消息目录
mkdir msg# 打开消息目录
cd msg# 创建消息文件
vim User.msg# 定义消息字段
string name
int32 age
三、修改编译配置
1、修改package.xml文件
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
2、修改CMakeLists.txt文件
# 添加消息文件
add_message_files(FILESUser.msg
)# 生成消息
generate_messages(DEPENDENCIESstd_msgs
)# 添加源文件
add_executable(publisher src/publisher.cpp)
add_executable(subscriber src/subscriber.cpp)# 添加依赖
add_dependencies(publisher ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS} ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(subscriber ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS} ${PROJECT_NAME}_generate_messages_cpp)# 连接catkin库
target_link_libraries(publisher ${catkin_LIBRARIES})
target_link_libraries(subscriber ${catkin_LIBRARIES})
四、创建发布者
#include <iostream>#include "ros/ros.h"
#include "demo/User.h"int main(int argc, char* argv[]) {std::string nodeName = "Publisher";ros::init(argc, argv, nodeName);ros::NodeHandle nodeHandle;std::string topicName = "demo3";uint32_t queueSize = 1000;const ros::Publisher &publisher = nodeHandle.advertise<demo::User>(topicName, queueSize); // 创建订阅者,指定消息类型demo::User msg; // 创建自定义消息msg.name = "publisher";msg.age = 30;ros::Rate rate(1);uint32_t messageId = 0;while (ros::ok() == true) {publisher.publish(msg); // 发布自定义消息rate.sleep();ROS_INFO("Publish topic message %d", messageId);++messageId;}return EXIT_SUCCESS;
}
运行效果:
五、创建订阅者
#include <iostream>#include "ros/ros.h"
#include "demo/User.h"void topicCallback(const demo::User::ConstPtr &message) {if (message.get() != nullptr) {const std::string &userName = message.get()->name;const uint32_t userAge = message.get()->age;ROS_INFO("Subscribe topic message success, name: %s, age: %d", userName.c_str(), userAge);}
}int main(int argc, char* argv[]) {std::string nodeName = "subscriber";ros::init(argc, argv, nodeName);ros::NodeHandle nodeHandle;std::string topicName = "demo3";uint32_t queueSize = 1000;const ros::Subscriber &subscriber = nodeHandle.subscribe<demo::User>(topicName, queueSize, topicCallback);ros::spin();return EXIT_SUCCESS;
}
运行效果:
六、消息类型对照表
msg字段类型 | C++数据类型 |
---|---|
bool | uint8_t |
int8 | int8_t |
int16 | int16_t |
int32 | int32_t |
int64 | int64_t |
uint8 | uint8_t |
uint16 | uint16_t |
uint32 | uint32_t |
uint64 | uint64_t |
float32 | float |
float64 | float |
string | std:string |
time | ros:Time |
duration | ros::Duration |