[牛人杂谈] 长延时函数的巧妙实现

[复制链接]
1014|1
 楼主| yiyigirl2014 发表于 2024-10-13 21:39 | 显示全部楼层 |阅读模式
  1. /**
  2.   * [url=home.php?mod=space&uid=247401]@brief[/url]      This function execute long delay function.
  3.   * @param[in]  us  Delay time.
  4.   * [url=home.php?mod=space&uid=266161]@return[/url]     None
  5.   * [url=home.php?mod=space&uid=1543424]@Details[/url]    Use the SysTick to generate the long delay time and the UNIT is in us.
  6.   *             The SysTick clock source is from HCLK, i.e the same as system core clock.
  7.   *             User can use SystemCoreClockUpdate() to calculate CyclesPerUs automatically before using this function.
  8.   */
  9. __STATIC_INLINE void CLK_SysTickLongDelay(uint32_t us)
  10. {
  11.     uint32_t delay;
  12.         
  13.     /* It should <= 335544us for each delay loop */
  14.     delay = 335544UL;

  15.     do
  16.     {
  17.         if(us > delay)
  18.         {
  19.             us -= delay;
  20.         }
  21.         else
  22.         {
  23.             delay = us;
  24.             us = 0UL;
  25.         }        
  26.         
  27.         SysTick->LOAD = delay * CyclesPerUs;
  28.         SysTick->VAL  = (0x0UL);
  29.         SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;

  30.         /* Waiting for down-count to zero */
  31.         while((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0UL);

  32.         /* Disable SysTick counter */
  33.         SysTick->CTRL = 0UL;
  34.    
  35.     }while(us > 0UL);
  36.    
  37. }
通过
do
{
if(us > delay)
{
us -= delay;
}
else
{
delay = us;
us = 0UL;
}


实现了任意数值的延时。当大于最大限制时候,就先执行限制,并扣掉该值,循环,直到小于最大计量。
chenqianqian 发表于 2024-10-14 08:10 来自手机 | 显示全部楼层
这种延时方式效率太低了
您需要登录后才可以回帖 登录 | 注册

本版积分规则

230

主题

3676

帖子

10

粉丝
快速回复 在线客服 返回列表 返回顶部