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

Protect `map()` against Usage Fault when `fromEnd == fromStart` #1193

Closed
ScruffR opened this issue Dec 1, 2016 · 0 comments · Fixed by #1248

Comments

@ScruffR
Copy link
Contributor

commented Dec 1, 2016

This is the current implementation (as used on AVR Arduinos without issue)

long map(long value, long fromStart, long fromEnd, long toStart, long toEnd)
{
  return (value - fromStart) * (toEnd - toStart) / (fromEnd - fromStart) + toStart;
}

But on STM32F µC an unhandled DIV/0 exception will cause a Usage Fault.
So checking for that and acting gracefully would be good.
e.g. like this

#include <math.h>

long map(long value, long fromStart, long fromEnd, long toStart, long toEnd)
{
  if (fromEnd == fromStart) return NAN;  // to prevent DIV/0 exception bail out with NaN
  return (value - fromStart) * (toEnd - toStart) / (fromEnd - fromStart) + toStart;
}

And if at that, maybe also add a double overload

double map(double value, double fromStart, double fromEnd, double toStart, double toEnd)
{
  if (fromEnd == fromStart) return NAN;  // to prevent DIV/0 exception bail out with NaN
  return (value - fromStart) * (toEnd - toStart) / (fromEnd - fromStart) + toStart;
}

Completeness:

  • Minimum test case added
  • Device, system and user firmware versions stated (as of 0.6.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.