ros编写发布者及订阅者代码
时间: 2024-04-29 17:24:22 浏览: 13
以下是一个简单的ROS发布者和订阅者的示例代码:
发布者:
```python
#!/usr/bin/env python
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
```
订阅者:
```python
#!/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():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber('chatter', String, callback)
rospy.spin()
if __name__ == '__main__':
listener()
```
在上述代码中,发布者使用了`rospy.Publisher`创建了一个名为`chatter`的话题,并将消息类型设置为`std_msgs/String`,并使用`rospy.Rate`指定发布频率。然后在循环中,发布了一个包含时间戳的字符串消息。
订阅者使用了`rospy.Subscriber`订阅了名为`chatter`的话题,并将回调函数设置为`callback`。`callback`函数在收到消息时输出消息内容。最后,使用`rospy.spin()`进入事件循环,以便可以持续接收消息。