#include "mytime.h"
// 初始化函数
void timer_delay_init(void) {
// 使能TIMER0时钟
rcu_periph_clock_enable(RCU_TIMER0);
// 配置PSC和ARR
// 假设系统时钟为100MHz,PSC=240,分频后1MHz (1计数=1微秒)
timer_prescaler_config(TIMER0, 240, TIMER_PSC_RELOAD_NOW);
// ARR=65535,最大计数周期
timer_autoreload_value_config(TIMER0, 65535);
// 使能更新事件自动重载
timer_auto_reload_shadow_enable(TIMER0);
timer_enable(TIMER0); // 使能定时器
}
// 毫秒延时函数
void time_delay_ms(uint32_t ms) {
uint32_t start = timer_counter_read(TIMER0); // 读取当前计数值
uint32_t elapsed = 0; // 已过去的时间
// 每次循环处理最大计数周期的延时
while (ms > 0) {
uint32_t current = timer_counter_read(TIMER0);
uint32_t delta;
// 处理计数器溢出情况
if (current >= start) {
delta = current - start;
} else {
// 溢出: current < start
delta = (65535 - start) + current + 1;
}
// 将微秒转换为毫秒
uint32_t ms_delta = delta / 1000;
if (ms_delta > 0) {
// 如果已经过了一段时间
if (ms_delta >= ms) {
// 已达到或超过所需延时
return;
}
ms -= ms_delta; // 减少剩余延时
elapsed += ms_delta; // 增加已过去的时间
start = timer_counter_read(TIMER0); // 重置起始时间
}
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/m0_58341340/article/details/149079822
|