K230 内部包含 6 个 Timer 硬件模块,最小定时周期为 1 微秒。通过这些定时器,可以实现精确的定时和周期性任务。
实验分别设定一个单次定时器和一个周期定时器,单次定时器只会触发一次回调函数,而周期定时器则会在程序进行的过程中,按照设定的周期时长不断地执行回调函数。
项目测试实验代码
- #【花雕动手做】CanMV K230 AI视觉识别模块之使用定时器计时
- # 项目功能:演示硬件定时器的使用,包括单次定时和周期定时两种模式
-
- # 导入定时器模块和时间模块
- from machine import Timer # 硬件定时器模块,提供精确的定时功能
- import time # 提供基础的延时功能
-
- def timer_callback_once(t):
- """
- 单次定时器回调函数
- One-shot timer callback function
-
- 参数说明 | Parameters:
- t: 触发回调的定时器对象 | Timer object that triggered the callback
-
- 功能特点 | Features:
- - 只执行一次后自动停止
- - 适用于延时执行特定任务
- - 常用于初始化、单次事件触发等场景
- """
- print("单次定时器触发了! Single shot timer triggered!")
- print(" 此消息只会显示一次 | This message will only appear once")
-
- def timer_callback_periodic(t):
- """
- 周期性定时器回调函数
- Periodic timer callback function
-
- 参数说明 | Parameters:
- t: 触发回调的定时器对象 | Timer object that triggered the callback
-
- 功能特点 | Features:
- - 按照固定周期重复执行
- - 适用于需要定期执行的任务
- - 常用于数据采集、状态监测、控制循环等
- """
- # 获取当前时间戳,精确到毫秒
- current_time = time.ticks_ms()
- print("周期定时器触发了! Periodic timer triggered!")
- print(f" 时间戳: {current_time} ms | Timestamp: {current_time} ms")
-
- try:
- # 实例化一个软定时器(虚拟定时器)
- # Initialize a virtual timer
- # 参数说明 | Parameters:
- # -1: 表示使用虚拟定时器(软件实现),不占用硬件定时器资源
- # 其他选项:0,1,2... 表示使用特定的硬件定时器
- timer = Timer(-1)
- print("定时器实例创建成功 | Timer instance created successfully")
-
- # ==================== 单次定时器演示 ====================
- # ==================== One-shot Timer Demo ====================
-
- # 配置单次模式定时器,周期为100ms
- # Configure one-shot timer with 100ms period
- print("\n--- 启动单次定时器 --- | --- Starting One-shot Timer ---")
- timer.init(period=100, # 定时周期:100毫秒
- mode=Timer.ONE_SHOT, # 模式:单次触发
- callback=timer_callback_once) # 回调函数
-
- print("单次定时器已启动,100ms后触发 | One-shot timer started, will trigger after 100ms")
-
- # 等待单次定时器触发完成
- # Wait for one-shot timer to complete
- # 等待200ms确保单次定时器有足够时间触发
- time.sleep(0.2)
- print("单次定时器测试完成 | One-shot timer test completed")
-
- # ==================== 周期定时器演示 ====================
- # ==================== Periodic Timer Demo ====================
-
- # 配置周期模式定时器,频率为1Hz(周期1秒)
- # Configure periodic timer with 1Hz frequency (1 second period)
- print("\n--- 启动周期定时器 --- | --- Starting Periodic Timer ---")
- timer.init(freq=1, # 频率:1Hz (等同于period=1000ms)
- mode=Timer.PERIODIC, # 模式:周期触发
- callback=timer_callback_periodic) # 回调函数
-
- print("周期定时器已启动,每秒触发一次 | Periodic timer started, will trigger every second")
- print("将运行4秒,预期触发4次 | Will run for 4 seconds, expected to trigger 4 times")
-
- # 让周期定时器运行4秒
- # Let periodic timer run for 4 seconds
- # 在此期间,定时器回调函数会每秒执行一次
- start_time = time.time()
- time.sleep(4)
- end_time = time.time()
- print(f"周期定时器运行结束,实际运行时间: {end_time - start_time:.2f} 秒")
- print(f"Periodic timer finished, actual runtime: {end_time - start_time:.2f} seconds")
-
- except Exception as e:
- # 异常处理:捕获并显示定时器操作过程中的任何错误
- # Exception handling: Catch and display any errors during timer operations
- print(f"定时器操作出错 | Error occurred: {e}")
- print("可能的原因 | Possible reasons:")
- print(" - 定时器资源已被占用 | Timer resource already in use")
- print(" - 参数设置超出范围 | Parameter out of range")
- print(" - 硬件定时器不可用 | Hardware timer not available")
-
- finally:
- # 释放定时器资源(无论是否发生异常都会执行)
- # Release timer resources (executed regardless of exceptions)
-
- # deinit()方法的重要作用:
- # - 停止定时器计数
- # - 释放硬件资源
- # - 取消回调函数注册
- # - 避免资源泄漏
- timer.deinit()
- print("\n定时器资源已释放 | Timer deinitialized")
- print("程序正常结束 | Program finished normally")
-
- """
- === 定时器技术详解 ===
-
- 1. 定时器类型:
- - 硬件定时器:精度高,不占用CPU,数量有限
- - 虚拟定时器:软件实现,精度稍低,数量无限制
-
- 2. 定时模式:
- - ONE_SHOT: 单次模式,触发一次后自动停止
- - PERIODIC: 周期模式,按固定间隔重复触发
-
- 3. 参数配置方式:
- - period: 以毫秒为单位设置周期
- - freq: 以赫兹为单位设置频率
- 注意:period和freq是互斥的,只能使用其中一个
-
- 4. 精度考虑:
- - 硬件定时器:微秒级精度
- - 虚拟定时器:毫秒级精度,受系统负载影响
-
- === 预期执行结果 ===
- 1. 创建定时器实例
- 2. 启动单次定时器,100ms后触发一次回调
- 3. 等待200ms确保单次定时完成
- 4. 启动周期定时器,每秒触发一次回调
- 5. 运行4秒,周期定时器触发约4次
- 6. 释放定时器资源,程序结束
-
- 实际输出示例:
- 定时器实例创建成功
- --- 启动单次定时器 ---
- 单次定时器已启动,100ms后触发
- 单次定时器触发了! Single shot timer triggered!
- 单次定时器测试完成
- --- 启动周期定时器 ---
- 周期定时器已启动,每秒触发一次
- 周期定时器触发了! 时间戳: 123456 ms
- 周期定时器触发了! 时间戳: 123456 ms
- 周期定时器触发了! 时间戳: 123456 ms
- 周期定时器触发了! 时间戳: 123456 ms
- 周期定时器运行结束,实际运行时间: 4.00 秒
- 定时器资源已释放
- 程序正常结束
- """
复制代码
代码解读:
1. 资源管理:定时器是系统稀缺资源,使用后必须通过deinit()释放
2. 模式选择:
◦ ONE_SHOT:适合延时任务、超时控制
◦ PERIODIC:适合周期性数据采集、控制循环
3. 精度权衡:硬件定时器精度高但数量有限,虚拟定时器灵活但精度低
4. 回调函数:在中断上下文中执行,应保持简短,避免阻塞操作
5. 参数配置:period(毫秒)和freq(赫兹)是设置定时周期的两种方式
这个示例完整展示了嵌入式系统中定时器的典型使用方法,是实时系统编程的基础技能。
实验串口返回情况


|