ROS(python)如何实现1个节点同时订阅2个话题,并实现话题同步,调用同一个callback

1. 创建talker1

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter1', String, queue_size=10)
    rospy.init_node('talker1', anonymous=True)
    rate = rospy.Rate(1) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world 1 %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()
if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

此节点创建了名为“talker1”的节点,并以每秒1个的频率发布名为“chatter1”的话题,话题内容为“hello word1+当前系统时间”
在这里插入图片描述

2.创建talker2

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import String

def talker():
    pub = rospy.Publisher('chatter2', String, queue_size=10)
    rospy.init_node('talker2', anonymous=True)
    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        hello_str = "hello world 2 %s" % rospy.get_time()
        rospy.loginfo(hello_str)
        pub.publish(hello_str)
        rate.sleep()

if __name__ == '__main__':
    try:
        talker()
    except rospy.ROSInterruptException:
        pass

此节点创建了名为“talker2”的节点,并以每秒10个的频率发布名为“chatter2”的话题,话题内容为“hello word2+当前系统时间”
在这里插入图片描述

3.创建listener

#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import message_filters

def callback(data1, data2):
    rospy.loginfo( "I heard %s %s", data1.data,data2.data)

def listener():
    rospy.init_node('listener', anonymous=True)
    t1= message_filters.Subscriber("chatter1", String)
    t2 =message_filters.Subscriber("chatter2", String)
    ts = message_filters.ApproximateTimeSynchronizer([t1, t2], 10, 1, allow_headerless=True)
    ts.registerCallback(callback)
    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

此节点创建了名为“listener”的节点,同时订阅chatter1和chasster2的话题,并利用message_filters实现话题同步,共同调用callback
在这里插入图片描述

  • 11
    点赞
  • 111
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值