ROS2教程(二)-创建发布者和订阅者(C++和Python版)
参考
官方参考:
http://docs.ros.org/en/foxy/Tutorials/Writing-A-Simple-Cpp-Publisher-And-Subscriber.html
中文翻译参考
https://zhuanlan.zhihu.com/p/353892419
https://zhuanlan.zhihu.com/p/353896706
C++版
注意工作空间不要命名太长,编译的时候会找不到功能包
1.0创建的功能包(cpp版)
ros2 pkg create --build-type ament_python py_pubsub
1.1获取发布者代码
cd cpp_pubsub/src
wget -O publisher_member_function.cpp https://raw.githubusercontent.com/ros2/examples/foxy/rclcpp/topics/minimal_publisher/member_function.cpp
1.2添加发布者的依赖
#package.xml
<depend>rclcpp</depend>
<depend>std_msgs</depend>
#CMakeLists.txt
find_package(rclcpp REQUIRED)
find_package(std_msgs REQUIRED)
add_executable(talker src/publisher_member_function.cpp)
ament_target_dependencies(talker rclcpp std_msgs)
install(TARGETS
talker
DESTINATION lib/${PROJECT_NAME})
1.3-获取订阅者代码及添加依赖
wget -O subscriber_member_function.cpp https://raw.githubusercontent.com/ros2/examples/foxy/rclcpp/topics/minimal_subscriber/member_function.cpp
add_executable(listener src/subscriber_member_function.cpp)
ament_target_dependencies(listener rclcpp std_msgs)
install(TARGETS
talker
listener
DESTINATION lib/${PROJECT_NAME})
1.4-编译运行订阅发布
rosdep install -i --from-path src --rosdistro foxy -y
colcon build --packages-select cpp_pubsub
. install/setup.bash
ros2 run cpp_pubsub talker
ros2 run cpp_pubsub listener
Python版
2.0创建功能包获取订阅发布(Python)
#在自己的工作空间下创建功能包
ros2 pkg create --build-type ament_python py_pubsub
#在src/py_pubsub/py_pubsub文件夹下放入
wget https://raw.githubusercontent.com/ros2/examples/foxy/rclpy/topics/minimal_publisher/examples_rclpy_minimal_publisher/publisher_member_function.py
wget https://raw.githubusercontent.com/ros2/examples/foxy/rclpy/topics/minimal_subscriber/examples_rclpy_minimal_subscriber/subscriber_member_function.py
2.1添加依赖
#package.xml
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
#setup.py
entry_points={
'console_scripts': [
'talker = py_pubsub.publisher_member_function:main',
'listener = py_pubsub.subscriber_member_function:main',
],
},
2.2编译运行
rosdep install -i --from-path src --rosdistro foxy -y
colcon build --packages-select py_pubsub
. install/setup.bash
ros2 run py_pubsub talker
ros2 run py_pubsub listener