Adding Information about traps with the function maps

Hi Arduino-Website-Maintenance-Team,

the map()-function screws up values if you use "bad" parameters.
In the section notes & warnings you should add this information
with a compilable example-code that demonstrates what happens.

if you try to use map in this wrong way

unsigned long rawToBeMapped = 1000000;
unsigned int mappedValue;

  mappedValue = map(rawToBeMapped, 123, 255, 0, 1023);

best regards Stefan

This is a programming error to use unsuitable types; The map function has nothing to do with it.

if I run

void setup()
{
  Serial.begin(115200);
  unsigned long rawToBeMapped = 1000000;
  unsigned int mappedValue;
  Serial.println(map(rawToBeMapped, 123, 255, 0, 1023));
  mappedValue = map(rawToBeMapped, 123, 255, 0, 1023);
  Serial.println(mappedValue);
}

void loop() {}

I get 7749046 and 15798 which seems right to me.

and if you print the hex values

void setup()
{
  Serial.begin(115200);Serial.println();
  unsigned long rawToBeMapped = 1000000;
  unsigned int mappedValue;
  Serial.println(map(rawToBeMapped, 123, 255, 0, 1023), HEX);
  mappedValue = map(rawToBeMapped, 123, 255, 0, 1023);
  Serial.println(mappedValue, HEX);
}

void loop() {}

you get 763DB6 and 3DB6 which shows what the compiler did, truncating the unsigned long's 4 bytes into the 2 LSB as per the C++ standard.

did I miss something?

the reason suggesting this is this thread

user jim81 gets negative values as the result of the map-function

best regards Stefan

The thread is long.
A negative value is a possible mapped value, there is nothing wrong with that.

Can you qualify if the negative value was
1/ a consequence of storing the result in a wrongly typed variable?
2/ a consequence of not understanding that map does not constrain its result?
3/ something else?

I'm unclear about the issue you are trying to nail

1 is a programming mistake. Often the compiler will issue a warning.
2. is already documented in the arduino doc

3 ?

see post in this thread