Arduino map() function can overflow

The way it is designed, it first multiplies given value on output range then divides by input range. All good until your given value is approaching limits for long type. Multilying it by range can get you over the threshold.

long map(long x, long in_min, long in_max, long out_min, long out_max)
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

map() - Arduino Reference mentions some specifics of the function but not a word about overflow. The long on 32bit SAM D21 is 4 bytes just like int, so trying to map 32bit integer can get you in trouble and return unexpected negative values.

The same is true for all mathematical operators. Overflows must be handled by the developer.