Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Computing time intervals with millis #72

Closed
dpgeorge opened this issue May 20, 2019 · 3 comments
Closed

[Bug] Computing time intervals with millis #72

dpgeorge opened this issue May 20, 2019 · 3 comments
Labels

Comments

@dpgeorge
Copy link

Describe the bug
When computing time intervals care must be taken with wrap around. Eg:

static inline void board_delay(uint32_t ms)
{
  uint32_t start_ms = board_millis();
  while( board_millis() < start_ms + ms) {}
}

If start_ms is close to 0xffffffff such that adding ms wraps it around then the function will most likely return straightaway.

@hathach
Copy link
Owner

hathach commented May 21, 2019

thanks again, PR #73 should fix this. Feel free to re-open & comment if you think it doesn't

hathach added a commit that referenced this issue May 21, 2019
fix #72 address overflow with board_delay
@dpgeorge
Copy link
Author

A simple way to fix it, due to 2's complement arithmetic overflow which is well-defined behaviour (at least in C99), is like this:

static inline void board_delay(uint32_t ms)
{
  uint32_t start_ms = board_millis();
  while( board_millis() - start_ms < ms) {}
}

Also, there are many places in the code that use this pattern, eg in examples/device/cdc_msc_hid/src/main.c:hid_task():

if ( board_millis() < start_ms + interval_ms) return;

hathach added a commit that referenced this issue May 21, 2019
hathach added a commit that referenced this issue May 21, 2019
better fix for #72 millis overflow
@hathach
Copy link
Owner

hathach commented May 21, 2019

Ah thank you, that is very neat 😄 . That proves how amazing Math is 🔢

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants