ros编写python节点
时间: 2025-03-06 07:27:24 浏览: 42
### 编写ROS节点的Python示例
为了创建一个简单的ROS节点,在Python中通常会导入`rospy`库并初始化节点。下面是一个发布者(Publisher)的例子,该例子展示了如何设置一个话题并将消息发送到这个话题上[^1]。
```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
```
这段代码定义了一个名为`talker`的函数,它会在启动时创建一个新的出版商对象来处理向`/chatter`主题发布的字符串消息。之后通过循环不断生成新的时间戳信息并通过调用`publish()`方法将其广播出去。
对于订阅者(Subscriber),可以按照如下方式实现:
```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)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
```
在这个版本里,当接收到新数据时就会触发回调函数`callback`,从而打印出所接收的信息。
阅读全文
相关推荐


















