How to deal with a wrapping counter in embedded C

后端 未结 11 1073
时光取名叫无心
时光取名叫无心 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 15:11

    Cast the result of unsigned subtraction to signed and compare to zero. Should handle overflow when you check it often enough (and your timeout is less than half the range of your timer).

    uint32_t timer( void);             // Returns the current time value
    uint32_t timeout;
    
    timeout = timer() + offset;
    
    // wait until timer() reaches or exceeds timeout value
    while ((int32_t)(timeout - timer()) > 0);
    

提交回复
热议问题