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
運行結果: