STM32 HAL库 SysTick->VAL和SysTick->LOAD 实现us延时

本文使用HAL库和STM32CubeMX配置时钟,使用 SysTick->LOAD 和 SysTick->VAL 来实现延时us和延时ms

M3内核中,SysTick计数器是24位递减计数器

计数范围2^24-1 到 0 ,然后重装载寄存器的值给SysTick计数器,重复下去

每来一个时钟,减1,STM32F1时钟来源为 HCLK(即AHB总线的时钟)72MHz

则 72次时钟过了1us,即 SystemCoreClock/1000000U 为 1us的定时计数值

获取上电以来的微秒数:

uint32_t micros(void)
{
    return (uwTick * 1000 + (SysTick->LOAD - SysTick->VAL) / (SystemCoreClock/1000000U));
}

其中,uwTick为上电以来的毫秒数,SysTick->VAL为定时器的当前值,SysTick->LOAD为系统滴答定时器的重装载值,SystemCoreClock/1000000U为1us的定时计数值。

获取上电以来的毫秒数:

uint32_t millis(void)
{
    return uwTick;
}

 微秒级延时:

void delay_us(uint32_t us)
{
    uint32_t total = 0;
    uint32_t target = (SystemCoreClock/1000000U) * us;
    int last = SysTick->VAL;
    int now = last;
    int diff = 0;
	while(1)
	{
		now = SysTick->VAL;
		diff = last - now;
    if(diff > 0)
    {
        total += diff;
    }
    else
    {
        total += diff + SysTick->LOAD;
    }
    if(total > target)
    {
        return;
    }
    last = now;
	}
}

毫秒级延时:

void delay_ms(uint32_t ms)
{
    uint32_t Stop_TimePoint = uwTick + ms;
    while(uwTick < Stop_TimePoint);
}

你可能感兴趣的:(stm32,嵌入式硬件,单片机)