ROS学习记录(三):使用自定义msg
ROS学习记录(三):使用自定义msg
话题通信自定义msg调用(C++)
需求 :
1
编写发布订阅实现,要求发布方以10HZ(每秒10次)的频率发布自定义消息,订阅方订阅自定义消息并将消息内容打印输出。
分析 : 与(一)话题通信的基本操作相同
vscode配置
为了方便代码提示以及避免误抛异常,需要先配置 vscode,将前面生成的 head 文件路径配置进 c_cpp_properties.json 的 includepath 属性:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"configurations": [
{
"browse": {
"databaseFilename": "",
"limitSymbolsToIncludedHeaders": true
},
"includePath": [
"${workspaceFolder}/**",
"/opt/ros/noetic/include/**",
"/usr/include/**",
"/usr/local/include/**",
"/home/deity/catkin_test_ws/devel/include/**"
],
"name": "ROS",
"intelliSenseMode": "gcc-x64",
"compilerPath": "/usr/bin/gcc",
"cStandard": "gnu17",
"cppStandard": "c++17",
"compilerArgs": [],
"compileCommands": "${workspaceFolder}/build/compile_commands.json"
}
],
"version": 4
}
1.发布方
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include"ros/ros.h"
#include"test_pubsub/Person.h"
/*
1.包含头文件
#include"test_pubsub/Person.h"
2.初始ros节点
3.创建节点句柄
4.创建发布对象
5.编写发布逻辑并发布数据
*/
int main(int argc, char *argv[])
{
// 2.初始ros节点
ros::init(argc,argv,"test_pub_person");
// 3.创建节点句柄
ros::NodeHandle nh;
// 4.创建发布对象
ros::Publisher pub = nh.advertise<test_pubsub::Person>("test_person",10);
// 5.编写发布逻辑并发布数据
//5.1定义发布数据
test_pubsub::Person person;
person.name = "张三";
person.age = 1;
person.height = 1.7;
//5.2设置发布频率
ros::Rate rate(1);
//5.3循环
while(ros::ok())
{
person.age++;
//发布数据
pub.publish(person);
//循环
rate.sleep();
// //回调函数此处没用到
// ros::spinOnce();
}
return 0;
}
2.订阅方
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include"ros/ros.h"
#include"std_msgs/String.h"
#include"test_pubsub/Person.h"
/*
发布实现:
1.包含头文件
#include"test_pubsub/Person.h"
2.初始ros节点
3.创建节点句柄
4.创建订阅对象
5.处理接收到的数据
6.spin()函数
*/
void test_person_callback(const test_pubsub::Person::ConstPtr &person){
ROS_INFO("订阅到的数据:%s,%d,%.2f",person->name.c_str(),person->age,person->height);
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
// 2.初始ros节点
ros::init(argc,argv,"test_sub_person");
// 3.创建节点句柄
ros::NodeHandle nh;
// 4.创建订阅对象
ros::Subscriber sub = nh.subscribe("test_person",10,test_person_callback);
// 5.处理接收到的数据
// 6.调用回调函数
ros::spin();
return 0;
}
3.配置 CMakeLists.txt
1
2
3
4
5
6
7
8
9
10
11
12
add_executable(test_pub_person src/test_pub_person.cpp)
add_executable(test_sub_person src/test_sub_person.cpp)
add_dependencies(test_pub_person ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(test_sub_person ${PROJECT_NAME}_generate_messages_cpp)
target_link_libraries(test_pub_person
${catkin_LIBRARIES}
)
target_link_libraries(test_sub_person
${catkin_LIBRARIES}
)
本文由作者按照 CC BY 4.0 进行授权