Files
ROS2_WS/Node_ws/py_node/py_node/py_node.py
2026-02-12 20:56:30 +08:00

33 lines
941 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 本程序用于使用python创建ROS2节点
# 并切每隔一秒钟输出一次当前时间
import rclpy
from rclpy.node import Node
class TimeNode(Node):
def __init__(self):
# 调用父类构造函数,创建一个名为'time_node'的节点
super().__init__('time_node')
# 创建一个定时器每隔1秒钟调用一次timer_callback函数
# 使用 timer 接收,防止被垃圾回收机制回收掉
self.timer = self.create_timer(1.0,self.timer_callback)
def timer_callback(self):
# 获取当前时间
now = self.get_clock().now()
# 输出当前时间到日志
self.get_logger().info(f'Current time: {now}')
def main():
# 初始化ROS2客户端库
rclpy.init()
# 创建一个ROS2节点
node = TimeNode()
# 保持节点运行,直到被关闭
rclpy.spin(node)
# 关闭节点并清理资源
rclpy.shutdown()