用Python实现ROS节点(这里也说明了用Python写ROS功能包也是需要CMakelists.txt的)

这里也说明了用Python写ROS功能包也是需要CMakelists.txt的

 

摘自:https://blog.csdn.net/u013832707/article/details/53980759

用Python实现ROS节点

持久决心 2017-01-02 18:28:59 21390 收藏 24

分类专栏: ROS Python 文章标签: python ROS

版权

 

ROS主要的编程语言不光是C++,也有Python。这里讲解如何利用Python实现ROS节点的编写。教程参考官网rospy_tutorials

1. 编写一个简单的发布者和订阅者

1创建工作空间

建立文件夹hello_rospy,再在该目录下建立子目录src,cd到该src目录,运行如下命令创建工作包

catkin_create_pkg beginner_tutorials std_msgs rospy roscpp

cd到src上层目录,编译并且source

cd ..
catkin_make
. devel/setup.bash

2编写发布者程序和订阅者程序

roscd beginner_tutorials/ 
mkdir scripts
cd scripts

在scripts目录下新建talker.py文件,填写如下内容:

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String
 
def talker():
     pub = rospy.Publisher('chatter', String, queue_size=10)
     rospy.init_node('talker', anonymous=True)
     rate = rospy.Rate(10) # 10hz
     while not rospy.is_shutdown():
         hello_str = "hello world %s" % rospy.get_time()
         rospy.loginfo(hello_str)
         pub.publish(hello_str)
         rate.sleep()
 
 if __name__ == '__main__':
     try:
         talker()
     except rospy.ROSInterruptException:
         pass

在scripts目录下新建listener.py文件,填写如下内容:

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

记得更改权限为可执行文件

3. 编译

修改Cmakelist.txt为如下:

cmake_minimum_required(VERSION 2.8.3)
project(beginner_tutorials)

## Find catkin macros and libraries
## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)
## is used, also find other catkin packages
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
)

catkin_package()

直接在工作空间运行catkin_make即可。

4. 运行

在3个终端中分别执行如下命令

roscore
rosrun beginner_tutorials talker.py
rosrun beginner_tutorials listener.py

结果如下:
这里写图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页