python怎么创建新节点_python ros 创建节点订阅robot_pose

建立文件夹hello_rospy,再在该目录下建立子目录src,cd到该src目录,运行如下命令创建工作包

catkin_create_pkg beginner_tutorials std_msgs rospy roscpp

pkg代表所属包名,name是文件名,type是脚本文件名称,output指定输出到屏幕

cd到src上层目录,编译并且source

cd ..

catkin_make

. devel/setup.bash

编写订阅者程序

roscd beginner_tutorials/mkdir scripts

cd scripts

在scripts目录下新建talker.py文件,填写如下内容

#!/usr/bin/env python

# license removedforbrevity

import rospyfromstd_msgs.msg import String

def talker():

pub= rospy.Publisher('chatter', String, queue_size=10)

rospy.init_node('talker', anonymous=True)

rate= rospy.Rate(10) # 10hzwhilenot 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 rospyfromstd_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 oneiskicked off. The

# anonymous=True flag means that rospy will choose a unique

# namefor our 'listener'node so that multiple listeners can

# run simultaneously.

rospy.init_node('listener', anonymous=True)

rospy.Subscriber("chatter", String, callback)

# spin() simply keeps pythonfrom exiting until this node isstopped

rospy.spin()if __name__ == '__main__':

listener()

记得更改权限为可执行文件

3. 编译

修改Cmakelist.txt为如下:

cmake_minimum_required(VERSION 2.8.3)

project(beginner_tutorials)

## Find catkin macros and libraries

##ifCOMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz)

##isused, also find other catkin packages

find_package(catkin REQUIRED COMPONENTS

roscpp

rospy

std_msgs

)

catkin_package()

直接在工作空间运行catkin_make即可

4. 运行

在3个终端中分别执行如下命令

roscore

rosrun beginner_tutorials talker.py

rosrun beginner_tutorials listener.py

结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值