这段代码中的 else 部分是什么意思?

hag*_*ago -2 c embedded arm

我正在浏览一些嵌入式编程链接 http://www.micromouseonline.com/2016/02/02/systick-configuration-made-easy-on-the-stm32/

【注意上面链接的代码作者已经更新了代码,delay_ms()文章中的实现不再使用下图所示的解决方案。】

并最终得到以下代码。这是针对 ARM 架构的,但基本上这是一个函数,它会导致作为参数传递的某些毫秒的延迟。所以我可以理解 if 条件,但为什么这里需要 else 条件?有人可以向我解释一下吗?

void delay_ms (uint32_t t)
{
  uint32_t start, end;
  start = millis();//This millis function will return the system clock in 
                   //milliseconds
  end = start + t;
  if (start < end) {
     while ((millis() >= start) && (millis() < end))
     { // do nothing } 
  }
 else{
     while ((millis() >= start) || (millis() < end)) 
     {
      // do nothing
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

Cli*_*ord 5

如果start + t导致溢出,end将小于start,因此该if部分处理该问题,并else处理“正常”情况。

说实话,确定它是否真的正确需要一些思考,但它几乎不值得,因为它是一种解决简单问题的过于复杂的方法。所需要的只是以下内容:

void delay_ms( uint32_t t )
{
    uint32_t start = millis() ;

    while( (uint32_t)millis() - start < t )
    { 
        // do nothing 
    } 
}
Run Code Online (Sandbox Code Playgroud)

要了解这start是如何工作的,请想象is0xFFFFFFFFtis 0x00000002,两毫秒后,millis()will0x00000001millis() - startwill 2

循环将在 时终止millis() - start == 3。可以说,您可能更喜欢millis() - start <= t,但是延迟将在几毫秒之间t-1t而不是至少 t几毫秒(tt+1)。您的选择,但重点是您应该比较计算和比较时间段,而不是尝试比较绝对时间戳值 - 简单得多。