Ros机器人之(六)话题消息的定义使用
自定义话题的发布流程
1.新建工作空间:
mkdir -p ~/cakin_one/src
cd cakin_one/src
catkin_init_workspace
cd ..
catkin_make
source devel/setup.bash
2.定义msg接口:
cd src/test_pkg
新建msg文件夹
cd msg
mkdir hello.msg
自定义msg内容
string name
uint8 sex
uint8 age
uint8 weight
uint8 unknown = 0
uint8 male = 1
uint8 female = 2
3.添加编译依赖和运行依赖:
package.xml修改:
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
cmakelists修改:
1.添加:
message_generation
2.添加:
add_message_files(FILES Person.msg)
generate_messages(DEPENDENCIES std_msgs)
3.添加:
CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
编译完成,在devel/include/test_pkg下会有hello.h生成
cd catkin_ws
catkin_make
4.订阅和发布消息:
发布:
新建hello_publisher.cpp
/*
发布话题
*/
#include<ros/ros.h>
#include"test_pkg/hello.h"
int main(int argc, char **argv){
ros::init(argc,argv,"hello_publisher");
ros::NodeHandle n;
ros::Publisher hello_info_pub=n.advertise<test_pkg::hello>("/hello_info",10);
ros::Rate loop_rate(1);
int count =0 ;
while(ros::ok()){
test_pkg::hello hello_msg;
hello_msg.name = "Tom";
hello_msg.age = 18;
hello_msg.weight = 65;
hello_msg.sex = test_pkg::hello::male;
hello_info_pub.publish(hello_msg);
ROS_INFO("Publish Person Info: name:%s age:%d weight:%d sex:%d", hello_msg.name.c_str(), hello_msg.age,hello_msg.weight, hello_msg.sex);
loop_rate.sleep();
}
}
cmakelists中添加
add_executable(hello_publisher src/hello_publisher.cpp)
target_link_libraries(hello_publisher ${catkin_LIBRARIES})
add_dependencies(hello_publisher ${PROJECT_NAME}_generate_messages_cpp)
订阅:
新建hello_subcriber.cpp
/**
* 订阅话题
*/
#include <ros/ros.h>
#include "test_pkg/hello.h"
// 接收到订阅的消息后,会进入消息回调函数
void helloInfoCallback(const test_pkg::hello::ConstPtr& msg)
{
// 将接收到的消息打印出来
ROS_INFO("Subcribe Hello Info: name:%s age:%d weight:%d sex:%d" ,
msg->name.c_str(), msg->age,msg->weight ,msg->sex);
}
int main(int argc, char **argv)
{
// 初始化ROS节点
ros::init(argc, argv, "hello_subscriber");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个Subscriber
ros::Subscriber hello_info_sub = n.subscribe("/hello_info", 10, helloInfoCallback);
// 循环等待回调函数
ros::spin();
return 0;
}
cmakelist中添加
add_executable(hello_subscriber src/hello_subscriber.cpp)
target_link_libraries(hello_subscriber ${catkin_LIBRARIES})
add_dependencies(hello_subscriber ${PROJECT_NAME}_generate_messages_cpp)
5.完成验证:
//编译
catkin_cmake
source devel/setup.bash
第一个终端:
roscore
第二个终端:
rosrun test_pkg hello_subscriber
第三个终端:
rosrun test_pkg hello_publisher
效果如下:
得到姓名、年龄、体重、性别信息