Files
JYF_STC15W4K_wireless_charge/Driver/timer4.c
2025-03-18 19:34:19 +08:00

45 lines
1.2 KiB
C
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.

#include "timer4.h"
u8 Timer4_OF = 0; // 定时器4溢出标志
// 定时器4初始化16位自动重载模式
void Timer4_Init(void) {
Timer4_Stop(); // 停止定时器4
T4T3M &= 0x0F; // 清除T4控制位
T4T3M |= 0x20; // 设置T4为1T模式
T4L = 0xD0; // 设置定时初始值
T4H = 0x8A; // 设置定时初始值 1ms@30MHz 1T
IE2 |= 0x40; // 使能定时器4中断
}
// 微秒级延时误差±0.3us
void Timer4_DelayUs(u16 us) {
u32 cycles = us * (FOSC / 1000000); // 计算所需时钟周期数
u16 reload = 65536 - (cycles / 1); // 1T模式下无需分频
T4H = reload >> 8; // 设置重载值高字节
T4L = reload & 0xFF;// 低字节
T4T3M |= 0x80; // 启动定时器4
while ( Timer4_OF != True ); // 等待TF4溢出标志置位
Timer4_OF = False; // 清除溢出标志
}
// 毫秒级延时(基于微秒级扩展)
void Timer4_DelayMs(u16 ms) {
while(ms--) {
Timer4_DelayUs(1000);
}
}
// 停止定时器4
void Timer4_Stop(void) {
T4T3M &= ~0x80; // 停止定时器4
}
// 定时器4中断服务程序
void Timer4_Isr(void) interrupt 20
{
Timer4_OF = True;
Timer4_Stop();
}