ROS之tf空间坐标广播与监听

坐标广播

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import roslib
roslib.load_manifest('test')
import rospy
import tf
import turtlesim.msg


def turtle_pose(msg, turtlename):#回调函数
    print msg.x, msg.y
    br = tf.TransformBroadcaster()
    # 将位置信息打包广播到world坐标系
    br.sendTransform((msg.x, msg.y, 0), tf.transformations.quaternion_from_euler(0, 0, msg.theta), rospy.Time.now(),turtlename, 'world')

if __name__ == '__main__':
    rospy.init_node('tf_broadcaster')
    turtlename='turtle1'
    #订阅turtle1的位置发布话题
    rospy.Subscriber('/%s/pose' % turtlename, turtlesim.msg.Pose, turtle_pose, turtlename)
    rospy.spin()

坐标监听

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import roslib

roslib.load_manifest('test')
import rospy
import tf
import math
import geometry_msgs.msg
import turtlesim.srv
import turtlesim.msg


def turtle_pose(msg, turtlename):
    br = tf.TransformBroadcaster()
    br.sendTransform((msg.x, msg.y, 0), tf.transformations.quaternion_from_euler(0, 0, msg.theta), rospy.Time.now(),
                     turtlename, 'world')


if __name__ == '__main__':
    rospy.init_node('tf_listener')
    listener = tf.TransformListener()
    rospy.wait_for_service('spawn')
    print 'GET'
    spawner = rospy.ServiceProxy('/spawn', turtlesim.srv.Spawn)
    response = spawner(2, 0, 1, 'turtle6')
    # turtle6产生后也必须监听位置,回调向world广播,才能加入tf体系。
    rospy.Subscriber('/turtle6/pose', turtlesim.msg.Pose, turtle_pose, 'turtle6')
    print response
    turtle_vel = rospy.Publisher('turtle6/cmd_vel', geometry_msgs.msg.Twist, queue_size=10)
    rate = rospy.Rate(10)
    while not rospy.is_shutdown():
        try:
            listener.waitForTransform('/turtle1', '/turtle6', rospy.Time(0), rospy.Duration(5), None)
            # 查询以turtle6为原点的turtle1的位置坐标,龟头方向为+x方向
            (trans, rot) = listener.lookupTransform('/turtle6', '/turtle1', rospy.Time(0))
        except (tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException), e:
            print e
            continue
        print trans[0], trans[1]

        angular = 4 * math.atan2(trans[1], trans[0])
        linear = 0.5 * math.sqrt(trans[0] ** 2 + trans[1] ** 2)
        cmd = geometry_msgs.msg.Twist()
        cmd.linear.x = linear
        cmd.angular.z = angular
        turtle_vel.publish(cmd)
        rate.sleep()

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值