Python为ROS编写一个简单的发布者和订阅者
1.创建工作空间
1.1建立文件夹hello_rospy,再在该目录下建立子目录src,并创建工作空间
mkdir -p ~/hello_rospy/src
cd ~/hello_rospy/src
catkin_init_workspace
1.2 编译
cd ~/hello_rospy/
catkin_make
1.3设置运行环境
echo “source ~/hello_rospy/devel/setup.bash” >> ~/.bashrc
1.4 检查运行环境(可以省略)
echo #ROS_PACKAGE_PATH
如果成功的话,输出内容应该包含,本空间的” …/devel/setup.bash”文件。
2.创建beginner_tutorials包
在src目录下创建beginner_tutorials包
cd ~/hello_rospy/src
catkin_create_pkg beginner_tutorials std_msgs rospy roscpp
3.编写发布者程序和订阅者程序
在beginner_tutorials 文件夹下面创建scripts文件夹,并在scripts文件夹下新建talker.py和listener.py两个文件
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()
更改文件权限为可执行文件
chmod +x talker.py
chmod +x listener.py
4. 编译
(Python编写可以省略)修改Cmakelist.txt为如下:
如果是按照上面编写的,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,编译:
catkin_make
5. 运行
cd #回到梗目录
roscore #启动ROS
rosrun beginner_tutorials talker.py
rosrun beginner_tutorials listener.py
运行结果: