HWD32F407-HAL_延时微妙和毫秒

如下函数是在调用HAL_Init()后可用的毫秒级延迟函数,在HAL库中跟时间有关的函数参数一般都是毫秒级。

void HAL_Delay(uint32_t Delay);

如果我们使用微妙级的延迟函数,可以使用如下:

#ifndef __DELAY_H
#define __DELAY_H

void delay_init(void);
void delay_us(uint32_t nus);
void delay_ms(uint16_t nms);

#endif
delay.h
#include "delay.h"

static uint32_t gt_fac_us = 0;       /* us延时倍乘数 us delay multiplier */

void delay_init(void)
{
    uint32_t sysfreq = HAL_RCC_GetSysClockFreq();
    gt_fac_us = sysfreq/1000000;
}

/*
 *
 * 函数名: delay_us
 * 功能描述: 延时nus,nus为要延时的us数(用时钟摘取法来做us延时).
 * 输入参数: nus
 * 输出参数: 无
 *
 * Function name: delay_us
 * Function description: Delay nus, nus is the number of us to be delayed (use clock extraction method to do us delay).
 * Input parameters: nus
 * Output parameters: None
*/

void delay_us(uint32_t nus)
{
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    /* LOAD的值  LOAD value*/
    uint32_t reload = SysTick->LOAD;
    /* 需要的节拍数  number of beats required*/    
    ticks = nus * gt_fac_us;
    /* 刚进入时的计数器值  Counter value when first entered*/
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            /* 这里注意一下SYSTICK是一个递减的计数器就可以了 Just note here that SYSTICK is a decrementing counter. */
            if (tnow < told)
            {
                tcnt += told - tnow;        
            }
            else
            {
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if (tcnt >= ticks)
            {
                /* 时间超过/等于要延迟的时间,则退出 If the time exceeds/is equal to the time to be delayed, exit */
                break;                      
            }
        }
    }
}


/*
 * 函数名: delay_ms
 * 功能描述: 延时nus,nus为要延时的us数(用时钟摘取法来做us延时).
 * 输入参数: nus
 * 输出参数: 无
 *
 * Function name: delay_ms
 * Function description: Delay nus, nus is the number of us to be delayed (use clock extraction method to do us delay).
 * Input parameters: nus
 * Output parameters: None
*/
void delay_ms(uint16_t nms)
{
    /* 普通方式延时  Normal mode delay*/
    delay_us((uint32_t)(nms * 1000));
}
delay.c
#include "delay.h"

int main(void)
{
    HAL_Init();
    
    delay_init();
    
    delay_us(10);
    
    while(1)
    {
        ;
    }
}
main.c

 

posted on 2026-03-30 11:10  LiveWithACat  阅读(3)  评论(0)    收藏  举报