You may have noticed that one downside to using the constrain function is that it makes for a large
dead area below the minimum value and above the maximum value. For example, as you turn the
potentiometer’s control arm, the output value stays at 250 until the output actually gets above 250.
This can prove impractical at times because it makes it more difficult to scale the input device to
produce meaningful output values.
One solution to that problem is to use the map function.
map(value, fromMin, fromMax, toMin, toMax);
The map function has five parameters:
value — The value to scale.
fromMin — The minimum value in the original range.
fromMax — The maximum value in the original range.
toMin — The minimum value in the mapped range.
toMax — The maximum value in the mapped range.
In a nutshell, the map function can alter the range of a value from one scale to another. For example, if
you want to change the range of the analog input to 0 through 255 rather than 0 through 1023, you use
the following.
input = map(analodRead(A0), 0, 1023, 0, 255);
Example Code
int analogInPin = A0; // Analog input pin that the potentiometer is attached to
int analogValue = 0; // variable to store the value coming from the analog pin
void setup() {
Serial.begin(9600); // initialize serial communications at 9600 bps:
}
void loop() {
analogValue = map(analogRead(A0), 0, 1023, 0, 255); // read the analog in value with map
Serial.print("analogValue = "); // print the results to the Serial Monitor:
Serial.println(analogValue);
delay(1000); // wait 1 seconds
}