新建ROS订阅者、发布者节点方法


做个正直的人

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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值