stm32 阻塞式延时 与 非阻塞式延时

这里写自定义目录标题

示例

阻塞场景

c 复制代码
    tickstart = HAL_GetTick();
    /* Wait till RTC is in INIT state and if Time out is reached exit */
    while ((READ_BIT(hrtc->Instance->ISR, RTC_ISR_INITF) == 0U) && (status != HAL_TIMEOUT))
    {
      if ((HAL_GetTick()  - tickstart) > RTC_TIMEOUT_VALUE)
      {
        status = HAL_TIMEOUT;
        hrtc->State = HAL_RTC_STATE_TIMEOUT;
      }

实现

1 阻塞式延时

c 复制代码
static uint32_t timer_tick, timer_period;
void LPTIM2_Init(uint16_t period_ms) // 低功耗定时器2初始化(周期近似1ms)
{	
	timer_period = period_ms;
	//...
}
void LPTIM2_IRQHandler(void) 	
{
    if ((LPTIM2->ISR & LPTIM_ISR_ARRM) != 0) {
		timer_tick_inc();
        LPTIM2->ICR |= LPTIM_ICR_ARRMCF; // 清除重载中断标志
    }
}
uint32_t timer_get_tick(void)
{
  return timer_tick;
}

void timer_tick_inc(void)
{
  timer_tick += timer_period;
}
/**
 * @brief  阻塞式延时函数,确保至少等待 m_delay 个时间单位。
 * @param  m_delay 期望延时的基数单位(单位由 timer_period 决定,如毫秒)。
 * @note   实际延时可能比 m_delay 多 1 个 timer_period,以保证最小等待时间。
 * 		   需要 LPTIM2_Init
 */
void timer_delay(uint32_t m_delay)
{
  uint32_t tickstart = timer_get_tick();
  uint32_t wait = m_delay;

  /* 增加一个 timer_period 避免在计时器更新边界时等待不足 */
  if (wait < 0xFFFFFFFFU) // 防止溢出
  {
    wait += timer_period; // 确保延时可靠性,但会使总延时增加一个 timer_period
  }

  /* 阻塞等待,直到满足时间差 */
  while ((timer_get_tick() - tickstart) < wait)
  {
  }
}

2 非阻塞式延时

复制代码
/**
 * @brief  检查自指定起始时间起是否已超时。
 * @param  start   起始时间点(需通过 timer_get_tick() 获取)。
 * @param  timeout 超时阈值(单位与 timer_get_tick() 的时间单位一致)。
 * @return bool    - true: 已超时
 *                 - false: 未超时
 */
bool is_timeout(unsigned int start, unsigned int timeout) {
    return timer_get_tick() - start > timeout;
}
相关推荐
lingzhilab41 分钟前
零知IDE——STM32F407VET6与ADS1115模数转换器实现多通道数据采集显示系统
stm32·单片机·开源
xxy.c4 小时前
基于IMX6ULL的时钟,定时器(EPIT,GPT)
单片机·嵌入式硬件·fpga开发
happygrilclh5 小时前
stm32L496 flash 分配
stm32·单片机·嵌入式硬件
古译汉书5 小时前
嵌入式铁头山羊STM32-各章节详细笔记-查阅传送门
数据结构·笔记·stm32·单片机·嵌入式硬件·个人开发
自由的好好干活6 小时前
从0开始使用LabVIEW操作数据采集卡-概述和新建新建项目
嵌入式硬件·labview
一枚码农~9 小时前
STM32红外与LED控制实战
单片机·嵌入式硬件
Heavy sea9 小时前
STM32定时器(寄存器与HAL库实现)
stm32·单片机
路过羊圈的狼10 小时前
STM32的HAL库驱动ADS124S08进行PT100温度采集
stm32·嵌入式硬件·mongodb
李永奉11 小时前
51单片机-实现红外遥控模块教程
单片机·嵌入式硬件·51单片机
辛集电子12 小时前
【STM32】位带操作
stm32·单片机·嵌入式硬件