cd ~/catkin_ws
catkin_make
编写发布器
roscd beginner_tutorials
mkdir scripts
cd scripts
touch talker.py
chmod +x talker.py (设置可执行)
nano talker.py
在talker.py输入:
#!/usr/bin/env python
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
(rospy API接口:http://docs.ros.org/api/rospy/html/)
roscore (另一终端)
rosrun beginner_tutorials talker.py (第一个终端)
talker.py输出[INFO] [1500369494.774872]: hello world 1500369494.77
rostopic echo /chatter (查看主题)
编写订阅器
roscd beginner_tutorials
cd scripts
touch listener.py
chmod +x listener.py
nano listener.py
在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 name are launched, the previous one is kicked off.
# 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()
cd ~/catkin_ws
catkin_make
在有talker.py运行时,listener.py输出[INFO] [1500369494.778061]: /listener_22987_1500369491424I heard hello world 1500369494.77
暂时不明白使用方法: rostopic pub -r 10 /chatter std_msgs/String “test" (也可以使用命令测试listener.py)
rqt_console (可视化窗口查看日志输出)
rqt_graph (可视化查看节点调用关系)
制作launch文件
roscd beginner_tutorials
mkdir -p bringup
cd bringup
touch talker-and-listener.launch
nano talker-and-listener.launch
在talker-and-listener.launch中输入:
<launch>
<node name="talker" pkg="beginner_tutorials" type="talker.py" />
<node name="listener" pkg="beginner_tutorials" type="listener.py" />
</launch>
roslaunch beginner_tutorials talker-and-listener.launch (运行launch文件)
输出:
PARAMETERS
* /rosdistro: kinetic
* /rosversion: 1.12.7
NODES
listener (beginner_tutorials/listener.py)
talker (beginner_tutorials/talker.py)
ROS_MASTER_URI=http://localhost:11311
core service [/rosout] found
process[talker-1]: started with pid [25891]
process[listener-2]: started with pid [25892]