Arduino project: Using the map() function for value scaling
When working with analog input pins on an Arduino, the acquired values are typically in the range of 0 to 1023. This is because the analog read resolution is 10 bits, resulting in a range of 2^10, which is 1024.
However, on certain ARM-based Arduino devices such as Arduino Zero, Arduino Due, and the Arduino MKR family, it is possible to extend the resolution to 12 bits by calling the analogReadResolution(12)
function. By doing so, you can acquire values ranging from 0 to 4095 instead of the default 0 to 1023.
To effectively map these acquired values to a different range, the Arduino language provides a convenient function called map()
. The function signature is as follows:
1 | int <newvalue> = map(<value>, <original_min>, <original_max>, <new_min>, <new_max>); |
Keep in mind that the map()
function returns an integer value, discarding any decimal points.
To illustrate the usage of the map()
function, let’s say you want to map the original 1024 values acquired through analog input to a set of only 10 values. This could be helpful if you have logic in your project that specifically handles 10 steps. You can achieve this by using the map()
function as shown below:
1 | int acquiredValue = analogRead(A1); |
In the above example, the acquired value from the analog pin is mapped from the range of 0 to 1023 to a new range of 0 to 9.
Here’s a complete example of using the map()
function:
1 | void setup() { |
By applying the map()
function, you can effectively reduce the input’s possible values to a restricted set of 10 values, ranging from 0 to 9.
tags: [“Arduino”, “map function”, “analog input”, “value scaling”, “ARM-based Arduino”, “analog read resolution.”]