当前位置:   article > 正文

ROS移动机器人——ROS基础知识与编程_ros机器人编程

ros机器人编程

此文章基于冰达机器人进行笔记整理,使用的环境为其配套环境,可结合之前的ROS,赵虚左老师的文章结合进行观看,后期也会进行整合

同时建议观看cn/ROS/Tutorials - ROS Wiki

官方教程

1. ROS安装

(1)配置ubuntu的软件和更新,允许安装不经认证的软件。

首先打开“软件和更新”对话框,具体可以在 Ubuntu 搜索按钮中搜索,确保勾选了"restricted", "universe," 和 "multiverse."

(2)设置安装源

来自国内中科大的安装源

sudo sh -c '. /etc/lsb-release && echo "deb http://mirrors.ustc.edu.cn/ros/ubuntu/ `lsb_release -cs` main" > /etc/apt/sources.list.d/ros-latest.list'

(3)设置key

sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654

(4)安装

首先需要更新 apt(以前是 apt-get, 官方建议使用 apt 而非 apt-get),apt 是用于从互联网仓库搜索、安装、升级、卸载软件或操作系统的工具。

sudo apt update

然后,再安装所需类型的 ROS:ROS 多个类型:Desktop-FullDesktopROS-Base。这里介绍较为常用的Desktop-Full(官方推荐)安装: ROS, rqt, rviz, robot-generic libraries, 2D/3D simulators, navigation and 2D/3D perception

sudo apt install ros-melodic-desktop-full

(5)配置环境变量

  1. echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
  2. source ~/.bashrc

(6)安装依赖

依赖相关工具

sudo apt install python-rosdep python-rosinstall python-rosinstall-generator python-wstool build-essential

安装rosdep

sudo apt install python-rosdep

初始化rosdep

  1. sudo rosdep init
  2. rosdep update

(7) sudo rosdep init初始化失败的解决办法

 2. ROS通信结构

ROS的通信结构是在OS层之上,通过TCP/IP协议协议实现

节点NODE与主节点Master

 master:相当于管理中心,node也需要现在master进行注册,node的通信也是由master进行引线,才能进行通信,一个ros计算图里只能有一个master。

节点:一个可执行程序进程,通常一个node负责机器人的一个功能,也可以通过同一局域网作用与不同的机器人

(2)四种通信方式

 (3)话题与服务

(4)动作

· goal - 用于向服务器发送目标

· cancel - 用于向服务器发送取消请求

· status - 用于通知客户端系统中每个目标的2当前状态

· feedback - 用于周期反馈目标的辅助信息

· rssult - 用于向client发送任务的执行结果,这个topic指挥发送一次

 (5)参数服务器

 并非是一个node,运行在master中,节点储存参数的地方

常用的shell命令

一图流:

常用图形工具

1.

rqt_graph

 显示节点与节点之间的关系

2.

rqt_plot

 用于显示变量,查找关注的目标,同时改变坐标尺度,当我们移动乌龟时,图像也会跟着移动

3.查看摄像头/图像

  1. //安装摄像头功能包
  2. sudo apt install ros-melodic-uvc-camera
  1. //运行
  2. rosrun uvc_camera uvc_camera_node

这个话题如果使用echo的方式打印出来,图像是无法直接看出的,所以我们需要借助工具

  1. rqt_image_view

同时选择我们的话题就可以查看

同时我们也可以使用roslaunch启动,roslaunch的机制如果我们没有启动roscore,他会自动帮我们启动,这个文件中为我们提供了launch,我们可以直接使用

roslaunch uvc_camera camera_node.launch

4. rviz

ros下,我们利用补齐就可以看到有许多工具,我们上面说明了一些重要的,同时还有一个rviz

他是一个强大的图像化显示工具,进行3d显示,2维也可以进行显示,我们之后再详细介绍

ROS坐标与TF变换

1.坐标定义法

2.rviz中显示坐标

 

当我们把两个小乌龟重合后,打开tf坐标

rosrun rqt_tf_tree rqt_tf_tree

可以有两个乌龟相对于中心坐标的位置

工作空间的创建与编译

 1.package.xml

该文件定义有关软件包的属性,例如软件包名称,版本号,作者,维护者以及对其他catkin软件包的依赖性。请注意,该概念类似于旧版 rosbuild 构建系统中使用的manifest.xml文件

  1. ​<?xml version="1.0"?>
  2. <!-- 格式: 以前是 1,推荐使用格式 2 -->
  3. <package format="2">
  4. <!-- 包名 -->
  5. <name>demo01_hello_vscode</name>
  6. <!-- 版本 -->
  7. <version>0.0.0</version>
  8. <!-- 描述信息 -->
  9. <description>The demo01_hello_vscode package</description>
  10. <!-- One maintainer tag required, multiple allowed, one person per tag -->
  11. <!-- Example: -->
  12. <!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
  13. <!-- 维护人员 -->
  14. <maintainer email="xuzuo@todo.todo">xuzuo</maintainer>
  15. <!-- One license tag required, multiple allowed, one license per tag -->
  16. <!-- Commonly used license strings: -->
  17. <!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  18. <!-- 许可证信息,ROS核心组件默认 BSD -->
  19. <license>TODO</license>
  20. <!-- Url tags are optional, but multiple are allowed, one per tag -->
  21. <!-- Optional attribute type can be: website, bugtracker, or repository -->
  22. <!-- Example: -->
  23. <!-- <url type="website">http://wiki.ros.org/demo01_hello_vscode</url> -->
  24. <!-- Author tags are optional, multiple are allowed, one per tag -->
  25. <!-- Authors do not have to be maintainers, but could be -->
  26. <!-- Example: -->
  27. <!-- <author email="jane.doe@example.com">Jane Doe</author> -->
  28. <!-- The *depend tags are used to specify dependencies -->
  29. <!-- Dependencies can be catkin packages or system dependencies -->
  30. <!-- Examples: -->
  31. <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
  32. <!-- <depend>roscpp</depend> -->
  33. <!-- Note that this is equivalent to the following: -->
  34. <!-- <build_depend>roscpp</build_depend> -->
  35. <!-- <exec_depend>roscpp</exec_depend> -->
  36. <!-- Use build_depend for packages you need at compile time: -->
  37. <!-- <build_depend>message_generation</build_depend> -->
  38. <!-- Use build_export_depend for packages you need in order to build against this package: -->
  39. <!-- <build_export_depend>message_generation</build_export_depend> -->
  40. <!-- Use buildtool_depend for build tool packages: -->
  41. <!-- <buildtool_depend>catkin</buildtool_depend> -->
  42. <!-- Use exec_depend for packages you need at runtime: -->
  43. <!-- <exec_depend>message_runtime</exec_depend> -->
  44. <!-- Use test_depend for packages you need only for testing: -->
  45. <!-- <test_depend>gtest</test_depend> -->
  46. <!-- Use doc_depend for packages you need only for building documentation: -->
  47. <!-- <doc_depend>doxygen</doc_depend> -->
  48. <!-- 依赖的构建工具,这是必须的 -->
  49. <buildtool_depend>catkin</buildtool_depend>
  50. <!-- 指定构建此软件包所需的软件包 -->
  51. <build_depend>roscpp</build_depend>
  52. <build_depend>rospy</build_depend>
  53. <build_depend>std_msgs</build_depend>
  54. <!-- 指定根据这个包构建库所需要的包 -->
  55. <build_export_depend>roscpp</build_export_depend>
  56. <build_export_depend>rospy</build_export_depend>
  57. <build_export_depend>std_msgs</build_export_depend>
  58. <!-- 运行该程序包中的代码所需的程序包 -->
  59. <exec_depend>roscpp</exec_depend>
  60. <exec_depend>rospy</exec_depend>
  61. <exec_depend>std_msgs</exec_depend>
  62. <!-- The export tag contains other, unspecified, tags -->
  63. <export>
  64. <!-- Other tools can request additional information be placed here -->
  65. </export>
  66. </package>

1.建立工作空间

mkdir catkin_ws

2.我们需要进入空间,创立src

cd catkin_ws/

3.我们的东西就要进入src目录下

mkdir src

4.将我们的包带进去

5.退出到目录

cd ..

 6.进行编译

catkin_make

7.我们还需要把工作空间加到环境变量里

vim .bashrc

ROS编程入门

工作空间的创建与编译

(1)ros文件内容介绍

WorkSpace --- 自定义的工作空间

    |--- build:编译空间,用于存放CMake和catkin的缓存信息、配置信息和其他中间文件。

    |--- devel:开发空间,用于存放编译后生成的目标文件,包括头文件、动态&静态链接库、可执行文件等。

    |--- src: 源码

        |-- package:功能包(ROS基本单元)包含多个节点、库与配置文件,包名所有字母小写,只能由字母、数字与下划线组成

            |-- CMakeLists.txt 配置编译规则,比如源文件、依赖项、目标文件

            |-- package.xml 包信息,比如:包名、版本、作者、依赖项...(以前版本是 manifest.xml)

            |-- scripts 存储python文件

            |-- src 存储C++源文件

            |-- include 头文件

            |-- msg 消息通信格式文件

            |-- srv 服务通信格式文件

            |-- action 动作格式文件

            |-- launch 可一次性运行多个节点 

            |-- config 配置信息

        |-- CMakeLists.txt: 编译的基本配置

1.package.xml

  1. //该文件定义有关软件包的属性​
  2. <?xml version="1.0"?>
  3. <!-- 格式: 以前是 1,推荐使用格式 2 -->
  4. <package format="2">
  5. <!-- 包名 -->
  6. <name>demo01_hello_vscode</name>
  7. <!-- 版本 -->
  8. <version>0.0.0</version>
  9. <!-- 描述信息 -->
  10. <description>The demo01_hello_vscode package</description>
  11. <!-- One maintainer tag required, multiple allowed, one person per tag -->
  12. <!-- Example: -->
  13. <!-- <maintainer email="jane.doe@example.com">Jane Doe</maintainer> -->
  14. <!-- 维护人员 -->
  15. <maintainer email="xuzuo@todo.todo">xuzuo</maintainer>
  16. <!-- One license tag required, multiple allowed, one license per tag -->
  17. <!-- Commonly used license strings: -->
  18. <!-- BSD, MIT, Boost Software License, GPLv2, GPLv3, LGPLv2.1, LGPLv3 -->
  19. <!-- 许可证信息,ROS核心组件默认 BSD -->
  20. <license>TODO</license>
  21. <!-- Url tags are optional, but multiple are allowed, one per tag -->
  22. <!-- Optional attribute type can be: website, bugtracker, or repository -->
  23. <!-- Example: -->
  24. <!-- <url type="website">http://wiki.ros.org/demo01_hello_vscode</url> -->
  25. <!-- Author tags are optional, multiple are allowed, one per tag -->
  26. <!-- Authors do not have to be maintainers, but could be -->
  27. <!-- Example: -->
  28. <!-- <author email="jane.doe@example.com">Jane Doe</author> -->
  29. <!-- The *depend tags are used to specify dependencies -->
  30. <!-- Dependencies can be catkin packages or system dependencies -->
  31. <!-- Examples: -->
  32. <!-- Use depend as a shortcut for packages that are both build and exec dependencies -->
  33. <!-- <depend>roscpp</depend> -->
  34. <!-- Note that this is equivalent to the following: -->
  35. <!-- <build_depend>roscpp</build_depend> -->
  36. <!-- <exec_depend>roscpp</exec_depend> -->
  37. <!-- Use build_depend for packages you need at compile time: -->
  38. <!-- <build_depend>message_generation</build_depend> -->
  39. <!-- Use build_export_depend for packages you need in order to build against this package: -->
  40. <!-- <build_export_depend>message_generation</build_export_depend> -->
  41. <!-- Use buildtool_depend for build tool packages: -->
  42. <!-- <buildtool_depend>catkin</buildtool_depend> -->
  43. <!-- Use exec_depend for packages you need at runtime: -->
  44. <!-- <exec_depend>message_runtime</exec_depend> -->
  45. <!-- Use test_depend for packages you need only for testing: -->
  46. <!-- <test_depend>gtest</test_depend> -->
  47. <!-- Use doc_depend for packages you need only for building documentation: -->
  48. <!-- <doc_depend>doxygen</doc_depend> -->
  49. <!-- 依赖的构建工具,这是必须的 -->
  50. <buildtool_depend>catkin</buildtool_depend>
  51. <!-- 指定构建此软件包所需的软件包 -->
  52. <build_depend>roscpp</build_depend>
  53. <build_depend>rospy</build_depend>
  54. <build_depend>std_msgs</build_depend>
  55. <!-- 指定根据这个包构建库所需要的包 -->
  56. <build_export_depend>roscpp</build_export_depend>
  57. <build_export_depend>rospy</build_export_depend>
  58. <build_export_depend>std_msgs</build_export_depend>
  59. <!-- 运行该程序包中的代码所需的程序包 -->
  60. <exec_depend>roscpp</exec_depend>
  61. <exec_depend>rospy</exec_depend>
  62. <exec_depend>std_msgs</exec_depend>
  63. <!-- The export tag contains other, unspecified, tags -->
  64. <export>
  65. <!-- Other tools can request additional information be placed here -->
  66. </export>
  67. </package>

2.CMakelists.txt

  1. //文件CMakeLists.txt是CMake构建系统的输入,用于构建软件包
  2. cmake_minimum_required(VERSION 3.0.2) #所需 cmake 版本
  3. project(demo01_hello_vscode) #包名称,会被 ${PROJECT_NAME} 的方式调用
  4. ## Compile as C++11, supported in ROS Kinetic and newer
  5. # add_compile_options(-std=c++11)
  6. ## Find catkin macros and libraries
  7. ## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
  8. ## is used, also find other catkin packages
  9. #设置构建所需要的软件包
  10. find_package(catkin REQUIRED COMPONENTS
  11. roscpp
  12. rospy
  13. std_msgs
  14. )
  15. ## System dependencies are found with CMake's conventions
  16. #默认添加系统依赖
  17. # find_package(Boost REQUIRED COMPONENTS system)
  18. ## Uncomment this if the package has a setup.py. This macro ensures
  19. ## modules and global scripts declared therein get installed
  20. ## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html
  21. # 启动 python 模块支持
  22. # catkin_python_setup()
  23. ################################################
  24. ## Declare ROS messages, services and actions ##
  25. ## 声明 ROS 消息、服务、动作... ##
  26. ################################################
  27. ## To declare and build messages, services or actions from within this
  28. ## package, follow these steps:
  29. ## * Let MSG_DEP_SET be the set of packages whose message types you use in
  30. ## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...).
  31. ## * In the file package.xml:
  32. ## * add a build_depend tag for "message_generation"
  33. ## * add a build_depend and a exec_depend tag for each package in MSG_DEP_SET
  34. ## * If MSG_DEP_SET isn't empty the following dependency has been pulled in
  35. ## but can be declared for certainty nonetheless:
  36. ## * add a exec_depend tag for "message_runtime"
  37. ## * In this file (CMakeLists.txt):
  38. ## * add "message_generation" and every package in MSG_DEP_SET to
  39. ## find_package(catkin REQUIRED COMPONENTS ...)
  40. ## * add "message_runtime" and every package in MSG_DEP_SET to
  41. ## catkin_package(CATKIN_DEPENDS ...)
  42. ## * uncomment the add_*_files sections below as needed
  43. ## and list every .msg/.srv/.action file to be processed
  44. ## * uncomment the generate_messages entry below
  45. ## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...)
  46. ## Generate messages in the 'msg' folder
  47. # add_message_files(
  48. # FILES
  49. # Message1.msg
  50. # Message2.msg
  51. # )
  52. ## Generate services in the 'srv' folder
  53. # add_service_files(
  54. # FILES
  55. # Service1.srv
  56. # Service2.srv
  57. # )
  58. ## Generate actions in the 'action' folder
  59. # add_action_files(
  60. # FILES
  61. # Action1.action
  62. # Action2.action
  63. # )
  64. ## Generate added messages and services with any dependencies listed here
  65. # 生成消息、服务时的依赖包
  66. # generate_messages(
  67. # DEPENDENCIES
  68. # std_msgs
  69. # )
  70. ################################################
  71. ## Declare ROS dynamic reconfigure parameters ##
  72. ## 声明 ROS 动态参数配置 ##
  73. ################################################
  74. ## To declare and build dynamic reconfigure parameters within this
  75. ## package, follow these steps:
  76. ## * In the file package.xml:
  77. ## * add a build_depend and a exec_depend tag for "dynamic_reconfigure"
  78. ## * In this file (CMakeLists.txt):
  79. ## * add "dynamic_reconfigure" to
  80. ## find_package(catkin REQUIRED COMPONENTS ...)
  81. ## * uncomment the "generate_dynamic_reconfigure_options" section below
  82. ## and list every .cfg file to be processed
  83. ## Generate dynamic reconfigure parameters in the 'cfg' folder
  84. # generate_dynamic_reconfigure_options(
  85. # cfg/DynReconf1.cfg
  86. # cfg/DynReconf2.cfg
  87. # )
  88. ###################################
  89. ## catkin specific configuration ##
  90. ## catkin 特定配置##
  91. ###################################
  92. ## The catkin_package macro generates cmake config files for your package
  93. ## Declare things to be passed to dependent projects
  94. ## INCLUDE_DIRS: uncomment this if your package contains header files
  95. ## LIBRARIES: libraries you create in this project that dependent projects also need
  96. ## CATKIN_DEPENDS: catkin_packages dependent projects also need
  97. ## DEPENDS: system dependencies of this project that dependent projects also need
  98. # 运行时依赖
  99. catkin_package(
  100. # INCLUDE_DIRS include
  101. # LIBRARIES demo01_hello_vscode
  102. # CATKIN_DEPENDS roscpp rospy std_msgs
  103. # DEPENDS system_lib
  104. )
  105. ###########
  106. ## Build ##
  107. ###########
  108. ## Specify additional locations of header files
  109. ## Your package locations should be listed before other locations
  110. # 添加头文件路径,当前程序包的头文件路径位于其他文件路径之前
  111. include_directories(
  112. # include
  113. ${catkin_INCLUDE_DIRS}
  114. )
  115. ## Declare a C++ library
  116. # 声明 C++ 库
  117. # add_library(${PROJECT_NAME}
  118. # src/${PROJECT_NAME}/demo01_hello_vscode.cpp
  119. # )
  120. ## Add cmake target dependencies of the library
  121. ## as an example, code may need to be generated before libraries
  122. ## either from message generation or dynamic reconfigure
  123. # 添加库的 cmake 目标依赖
  124. # add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
  125. ## Declare a C++ executable
  126. ## With catkin_make all packages are built within a single CMake context
  127. ## The recommended prefix ensures that target names across packages don't collide
  128. # 声明 C++ 可执行文件
  129. add_executable(Hello_VSCode src/Hello_VSCode.cpp)
  130. ## Rename C++ executable without prefix
  131. ## The above recommended prefix causes long target names, the following renames the
  132. ## target back to the shorter version for ease of user use
  133. ## e.g. "rosrun someones_pkg node" instead of "rosrun someones_pkg someones_pkg_node"
  134. #重命名c++可执行文件
  135. # set_target_properties(${PROJECT_NAME}_node PROPERTIES OUTPUT_NAME node PREFIX "")
  136. ## Add cmake target dependencies of the executable
  137. ## same as for the library above
  138. #添加可执行文件的 cmake 目标依赖
  139. add_dependencies(Hello_VSCode ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
  140. ## Specify libraries to link a library or executable target against
  141. #指定库、可执行文件的链接库
  142. target_link_libraries(Hello_VSCode
  143. ${catkin_LIBRARIES}
  144. )
  145. #############
  146. ## Install ##
  147. ## 安装 ##
  148. #############
  149. # all install targets should use catkin DESTINATION variables
  150. # See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html
  151. ## Mark executable scripts (Python etc.) for installation
  152. ## in contrast to setup.py, you can choose the destination
  153. #设置用于安装的可执行脚本
  154. catkin_install_python(PROGRAMS
  155. scripts/Hi.py
  156. DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
  157. )
  158. ## Mark executables for installation
  159. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_executables.html
  160. # install(TARGETS ${PROJECT_NAME}_node
  161. # RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
  162. # )
  163. ## Mark libraries for installation
  164. ## See http://docs.ros.org/melodic/api/catkin/html/howto/format1/building_libraries.html
  165. # install(TARGETS ${PROJECT_NAME}
  166. # ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  167. # LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  168. # RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION}
  169. # )
  170. ## Mark cpp header files for installation
  171. # install(DIRECTORY include/${PROJECT_NAME}/
  172. # DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
  173. # FILES_MATCHING PATTERN "*.h"
  174. # PATTERN ".svn" EXCLUDE
  175. # )
  176. ## Mark other files for installation (e.g. launch and bag files, etc.)
  177. # install(FILES
  178. # # myfile1
  179. # # myfile2
  180. # DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
  181. # )
  182. #############
  183. ## Testing ##
  184. #############
  185. ## Add gtest based cpp test target and link libraries
  186. # catkin_add_gtest(${PROJECT_NAME}-test test/test_demo01_hello_vscode.cpp)
  187. # if(TARGET ${PROJECT_NAME}-test)
  188. # target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME})
  189. # endif()
  190. ## Add folders to be run by python nosetests
  191. # catkin_add_nosetests(test)

(2)话题通信基本操作

在模型实现中,ROS master 不需要实现,而连接的建立也已经被封装了,需要关注的关键点有三个:

  1. 发布方
  2. 接收方
  3. 数据(此处为普通文本)

所以我们需要实现的流程为:

  1. 编写发布方实现;
  2. 编写订阅方实现;
  3. 编辑配置文件;
  4. 编译并执行。

需求:实现通信,一方接受,一方发送

消息发布方: helloworld + 计数

      

  1. // 1.包含头文件
  2. #include "ros/ros.h"
  3. #include "std_msgs/String.h" //普通文本类型的消息
  4. #include <sstream>
  5. int main(int argc, char *argv[])
  6. {
  7. //设置编码
  8. setlocale(LC_ALL,"");
  9. //2.初始化 ROS 节点:命名(唯一)
  10. // 参数1和参数2 后期为节点传值会使用
  11. // 参数3 是节点名称,是一个标识符,需要保证运行后,在 ROS 网络拓扑中唯一
  12. ros::init(argc,argv,"talker");
  13. //3.实例化 ROS 句柄
  14. ros::NodeHandle nh;//该类封装了 ROS 中的一些常用功能
  15. //4.实例化 发布者 对象
  16. //泛型: 发布的消息类型
  17. //参数1: 要发布到的话题
  18. //参数2: 队列中最大保存的消息数,超出此阀值时,先进的先销毁(时间早的先销毁)
  19. ros::Publisher pub = nh.advertise<std_msgs::String>("chatter",10);
  20. //5.组织被发布的数据,并编写逻辑发布数据
  21. //数据(动态组织)
  22. std_msgs::String msg;
  23. // msg.data = "你好啊!!!";
  24. std::string msg_front = "Hello 你好!"; //消息前缀
  25. int count = 0; //消息计数器
  26. //逻辑(一秒10次)
  27. ros::Rate r(1);
  28. //节点不死
  29. while (ros::ok())
  30. {
  31. //使用 stringstream 拼接字符串与编号
  32. std::stringstream ss;
  33. ss << msg_front << count;
  34. msg.data = ss.str();
  35. //发布消息
  36. pub.publish(msg);
  37. //加入调试,打印发送的消息
  38. ROS_INFO("发送的消息:%s",msg.data.c_str());
  39. //根据前面制定的发送贫频率自动休眠 休眠时间 = 1/频率;
  40. r.sleep();
  41. count++;//循环结束前,让 count 自增
  42. //暂无应用
  43. ros::spinOnce();
  44. }
  45. return 0;
  46. }

编辑法2(冰达)

1. 建立文件 talker.cpp 用于通信的发布者

2. 包含头文件

  1. // ros头文件
  2. #include "ros/ros.h"
  3. //普通文本类型的消息
  4. #include "std_msgs/String.h"

3. 写标准main函数、(m)

  1. int main(int argc,char **argv)
  2. {
  3. //初始化ros,三个参数,最后一个为节点名称
  4. ros::init(argc,argv,"talker");
  5. //不能在一个ros中运行两个节点,所以要创建句点
  6. ros:NodeHandle n;
  7. // 创建发布器,最后为发布类型string,发布的消息名为chatter,1000个,储存我们的消息
  8. ros:Publisher chatter_pub = n.advertise<std_msgs::String>("chatter",1000);
  9. //创建一个循环,这里用10hz
  10. ros:Rate loop_rate(10);
  11. //记数,查看一共有多少个话题
  12. int count = 0;
  13. //写一个死循环,让他发送消息
  14. while(ros::ok()) // 当收到ctrl + c就会停止
  15. {
  16. std_msgs::String msg; //名字为msg
  17. std:stringstream ss; // 命名消息
  18. ss<<"hello world"<<count; //消息格式(内容)
  19. msg.data = ss.str(); //将ss赋值给数据data
  20. ROS_INFO("%s",msg.data.c_str());
  21. chatter_pub.publish(msg);
  22. ros::spinOnce();
  23. loop_rate.sleep();
  24. count++:
  25. }
  26. }

接下来我们来看看订阅者

  1. #include "ros/ros.h"
  2. #include "std_msgs/String"
  3. void chatterCallback(const std_msgs::StringConstPtr&msg)
  4. {
  5. ROS_INFO("i heard:[%s] ",msg.data.c_str()); //以字符串形式
  6. }
  7. int main(int argc,char **argv)
  8. {
  9. ros::init(argc,argv, "Listener");
  10. ros::NodeHandle n;
  11. ros::Subcriber sub=n.subcribe("chatter",1000,chatterCallback);
  12. ros::spin(); //循环
  13. return 0;
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/401054?site
推荐阅读
相关标签
  

闽ICP备14008679号