How to deal with a wrapping counter in embedded C

后端 未结 11 1106
时光取名叫无心
时光取名叫无心 2021-02-05 14:23

I need to deal with a counter that gives me ticks for my application. The counter is 32bits so what i need to know is how to deal with it when it wraps. for example:

I h

11条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 14:50

    If you use unsigned variables to store your counter and timer expiry time, then you can simply use this test:

    if (current_time - expiry_time < 0x80000000UL)
        /* timer has expired */
    

    This assumes that you test for expiry at least once every 0x80000000 ticks, and that your longest timer is set to expire less than 0x80000000 ticks into the future.

提交回复
热议问题