c - 减去两个 uint32_t 变量给出一种溢出的结果?

标签 c embedded overflow

我正在编写一个 stm8s 微 Controller ,我正在使用 STVD IDE 和 COSMIC 编译器。

两个uint32_t 变量相减的结果保存在另一个uint32_t 变量中。有时这个过程会产生一个奇怪的值。这个奇怪的值始终是预期值,最高有效位设置为 1s

这是我的代码片段:

static uint32_t lastReceivedLed = 0;
uint32_t timeSinceLast = 0;

timeSinceLast = IL_TimTimeNow() - lastReceivedLed;

if(timeSinceLast > 2500U)
{
      Inhibitor = ACTIVE;  // HERE IS MY BREAKPOINT
}

IL_TimTimeNow() 是这样定义的:

volatile uint32_t IL_TimNow = 0;

uint32_t IL_TimTimeNow(void)
{
    return IL_TimNow; // Incremented in timer ISR
}

以下是调试 session 中的一些实际值:

enter image description here

timeSinceLast 应该是 865280 - 865055 = 225 = 0xE1

但是编译器计算出来的结果是4294967265 = 0xFFFFFFFE1

请注意,最低有效字节是正确的,而其余字节在编译器的结果中设置为 1s!!

另请注意,这种情况只会偶尔发生一次。否则,它会按预期完美运行。

这是溢出了吗?什么会导致这种情况?

最佳答案

调试器中显示的值是:

  • IL_TimNow = 865280
  • lastReceivedLed = 865055
  • timeSinceLast = 4294967265

请注意,4294967265 也是将 -31 转换为 uint32_t 时得到的结果。这表明 IL_TimTimeNow() 在减法之前返回的 IL_TimNow 的值实际上是 lastReceivedLed - 31,即 865055 - 31,这是 865024。

调试器中显示的 IL_TimNow 值 (865280) 与减法前的 IL_TimNow 值 (865024) 之间的差值为 256。此外,两个值的最低有效 8 位均为零。这表明在最低有效字节回绕到 0 并且下一个字节递增时正在读取该值。 IL_TimTimeNow() 中的注释说 //Incremented in timer ISR。由于 8 位微 Controller 一次只能读取一个字节,因此似乎在函数读取 IL_TimNow 的四个字节时发生了定时器 ISR。

有两种方法可以解决这个问题。第一种方法是在读取 IL_TimNow 的值时禁用 IL_TimTimeNow() 中的定时器中断。所以 IL_TimTimeNow() 函数可以改成这样:

uint32_t IL_TimTimeNow(void)
{
    uint32_t curTime;

    disable_timer_interrupt();
    curTime = IL_TimNow;
    enable_timer_interrupt();
    return curTime;
}

但是,您需要检查暂时禁用定时器中断只会导致中断被延迟,而不是完全跳过(否则您将失去定时器滴答声)。

解决该问题的另一种方法是继续读取 IL_TimTimeNow() 中的 IL_TimNow,直到获得两个相同的值。所以 IL_TimTimeNow() 函数可以改成这样:

uint32_t IL_TimTimeNow(void)
{
    uint32_t prevTime, curTime;

    curTime = IL_TimNow;
    do
    {
         prevTime = curTime;
         curTime = IL_TimNow;
    } while (curTime != prevTime);
    return curTime;
}

do ...while 循环通常会有一个迭代,读取 IL_TimNow 两次。偶尔会出现两次循环迭代,读取IL_TimNow 3 次。实际上,我不希望循环迭代超过两次,但该函数也可以处理。

上面的一个不太安全但可能稍微快一点的版本是当最低有效字节为 0 时只读取 IL_TimNow 两次:

uint32_t IL_TimTimeNow(void)
{
    uint32_t curTime;

    curTime = IL_TimNow;
    if ((curTime & 0xFF) == 0)
    {
        // Least significant byte possibly just wrapped to 0
        // so remaining bytes may be stale. Read it again to be sure.
        curTime = IL_TimNow;
    }
    return curTime;
}

如果性能不是问题,请使用更安全的版本之一。

关于c - 减去两个 uint32_t 变量给出一种溢出的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56583768/

相关文章:

html - 水平溢出容器 div 而不是垂直溢出

c - C中的堆缓冲区溢出

json - JsonConvert.DeserializeXmlNode 中的 StackOverflowException

c - 为什么不获取驱动程序读写函数的偏移量?

C 结构体中的增量计数器

linux - 更改嵌入式 linux 内核代码

embedded - blackfin bf561 FreeRTOS 实现在加载任务时在运行时失败

C# GUI 在 C 硬计算引擎之上

c - "comparison between signed and unsigned integer expressions"仅包含无符号整数

c - Visual Studio - 编译错误