当前位置:   article > 正文

python实现ROS的TOPIC通信_ros topic搜索python

ros topic搜索python

ROS 版本是

  1. PARAMETERS
  2. * /rosdistro: melodic
  3. * /rosversion: 1.14.12

utuntu 系统版本 18.04

1.工作空间是存放工程开发的相关文件的文件夹

src:代码空间

build:编译空间

devel:开发空间

install:安装空间

2.创作工作空间指令

  1. $mkdir -p ~/catkin_ws/src
  2. $cd ~/catkin_ws/src
  3. $catkin_init_workspace

编译工作空间(注意编译工作空间一定要在工作空间的根目录下)

  1. $ cd ~/catkin_ws/
  2. $ catkin_make

设置环境变量

$ source devel/setup.bash

检查环境变量

$ echo $ROS_PACKAGE_PATH

3 创建功能包

创建功能包指令

  1. $ cd ~/catkin_ws/src
  2. $ catkin_create_pkg test_pkg std_msgs rospy roscpp

编译功能包

  1. $ cd ~/catkin_ws
  2. $ catkin_make
  3. $ source ~/catkin_ws/devel/setup.bash

4. 创建Topic的订阅发布方法

创建源码文件夹

$ mkdir ~/catkin_ws/src/test_pkg/scripts

创建publisher的python文件

  1. $ cd ~/catkin_ws/src/test_pkg/scripts
  2. $ vim talker.py

talker.py内容

  1. #!/usr/bin/env python
  2. import rospy
  3. from std_msgs.msg import String
  4. def talker():
  5. pub = rospy.Publisher('chatter', String, queue_size=10)
  6. rospy.init_node('talker', anonymous=True)
  7. rate = rospy.Rate(10) # 10hz
  8. while not rospy.is_shutdown():
  9. hello_str = "hello world %s" % rospy.get_time()
  10. rospy.loginfo(hello_str)
  11. pub.publish(hello_str)
  12. rate.sleep()
  13. if __name__ == '__main__':
  14. try:
  15. talker()
  16. except rospy.ROSInterruptException:
  17. pass

 创建订阅的python文件

  1. $ cd ~/catkin_ws/src/test_pkg/scripts
  2. $ vim listener.py

listener.py的内容

  1. #!/usr/bin/env python
  2. import rospy
  3. from std_msgs.msg import String
  4. def callback(data):
  5. rospy.loginfo(rospy.get_caller_id() + 'I heard %s', data.data)
  6. def listener():
  7. # In ROS, nodes are uniquely named. If two nodes with the same
  8. # name are launched, the previous one is kicked off. The
  9. # anonymous=True flag means that rospy will choose a unique
  10. # name for our 'listener' node so that multiple listeners can
  11. # run simultaneously.
  12. rospy.init_node('listener', anonymous=True)
  13. rospy.Subscriber('chatter', String, callback)
  14. # spin() simply keeps python from exiting until this node is stopped
  15. rospy.spin()
  16. if __name__ == '__main__':
  17. listener()

python不需要编译CMakeList.txt文件

直接运行roscore,以及listener.py,talker.py

运行ros程序

$ roscore

打开新的Terminal,运行 talker

  1. $ cd ~/catkin_ws/src/test_pkg/scripts
  2. $ python talker.py

打开新的Terminal,运行 listener

  1. $ cd ~/catkin_ws/src/test_pkg/scripts
  2. $ python listener.py

运行结果

 

 

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

闽ICP备14008679号