61 lines
1.3 KiB
C
61 lines
1.3 KiB
C
// Delay.c (修改后)
|
|
#include "stm32f10x.h"
|
|
|
|
// 1. 添加一个全局变量,用于记录毫秒数
|
|
// 注意:不使用static,以便中断函数可以访问
|
|
volatile uint32_t g_time_ms = 0;
|
|
|
|
/**
|
|
* @brief 初始化SysTick定时器,配置为1ms中断一次
|
|
*/
|
|
void Delay_Init(void)
|
|
{
|
|
// 配置SysTick为1ms中断一次。SystemCoreClock通常是72MHz。
|
|
if (SysTick_Config(SystemCoreClock / 1000))
|
|
{
|
|
// 如果配置失败,进入死循环
|
|
while (1);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief 获取自启动以来的毫秒数
|
|
* @retval 当前的毫秒时间戳
|
|
*/
|
|
uint32_t Get_Time_ms(void)
|
|
{
|
|
return g_time_ms;
|
|
}
|
|
|
|
|
|
// --- 以下是你原本就有的阻塞式延时函数,保持不变 ---
|
|
|
|
void Delay_us(uint32_t xus)
|
|
{
|
|
SysTick->LOAD = 72 * xus;
|
|
SysTick->VAL = 0x00;
|
|
SysTick->CTRL = 0x00000005;
|
|
while(!(SysTick->CTRL & 0x00010000));
|
|
SysTick->CTRL = 0x00000004;
|
|
}
|
|
|
|
void Delay_ms(uint32_t xms)
|
|
{
|
|
// 使用SysTick计时器实现精确延时
|
|
uint32_t start_time = g_time_ms;
|
|
while((g_time_ms - start_time) < xms) {
|
|
// 等待
|
|
}
|
|
}
|
|
|
|
void Delay_s(uint32_t xs)
|
|
{
|
|
while(xs--)
|
|
{
|
|
Delay_ms(1000);
|
|
}
|
|
}
|
|
|
|
// 在这个文件的末尾,或者在 stm32f10x_it.c 中,你需要 SysTick_Handler
|
|
// 为了集中管理,我们把它放在 stm32f10x_it.c
|