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
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐