文章目录
做个正直的人
1、新建一个该项目的工作空间,并在其中创建一个文件夹src
mkdir my_ws
cd my_ws
mkdir src
2、进入src文件夹,并在其中创建一个package,运行如下命令即可
catkin_create_pkg beginner_tutorials std_msgs rospy roscpp
其中catkin_create_pkg表示创建一个package并进行初始化
beginner_tutorials是创建的package的名字
std_msgs rospy roscpp表示该package需要用到的一些属性,std_msg表示需要用到标准输入输出消息
3、返回上一层,编译,并source
cd ..
catkin_make
sudo gedit .bashrc
在打开的文件中加入下面这一行
source ~/my_ws/devel/setup.bash
否则的话,在你想要运行rosrun的时候,就找不到对应的文件了
然后把.bashrc文件source一下
4、编写发布者程序和订阅者程序
cd src/beginner_tutorials
mkdir scripts
在scripts里面创建两个.py文件,一个是talker.py,一个是listener.py
5、在这里最好把这两个文件的权限修改一下,不然可能在运行的时候,程序异常终止
sudo chmod 777 talker.py listen.py
6、修改Cmakelist.txt文件
只需要把package的名字修改为你的package的名字即可
7、回到工作空间,也就是src的上一层目录
再次运行
catkin_make
8、运行
打开新终端,运行
roscore
打开新终端,运行发布者程序
rosrun beginner_tutorials talker.py
打开新终端,运行订阅者程序
rosrun beginner_tutorials listener.py
talker.py的内容如下所示(务必注意,python对空格非常敏感)
#!/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
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()