Arduino programming guide series
The Arduino "map" function
The map() function makes it easy to convert numbers from one range to another. Here's a simple example of its usage.
The map() function makes it easy to convert a value from one range into a proportional value of another range.
We can sample the potentiometer with one of Arduino’s analog inputs, which have a resolution of 1024 values (10 bits). For this purpose, we use the analogRead() function.
To control the motor, we use Pulse Width Modulation which has a resolution of 256 values (8 bits). For this purpose, we use the analogWrite() function.
Therefore, whichever value we measure in the analog inputs, we have to convert it to a proportional value inside the PWM range of values.
Using the map function, this is as simple as this:
int mappedVal = map(analogRead(0),0,1023,0,254);
Say that the analogRead() function read the value "328" from the potentiometer. The call to the map() function will look like this (I have replaced the call to analogRead() with the explicit value "328"):
int mappedVal = map(328,0,1023,0,253);
The result of the mapping will be 81, which will be stored in the mappedVal variable.
Would you like to try this yourself? Here's my Tinkercad project. It contains a virtual Arduino Uno with a simple sketch that contains the map() function example.
"Arduino programming" series
Jump to another article
New to the Arduino?
Arduino Step by Step Getting Started is our most popular course for beginners.
This course is packed with high-quality video, mini-projects, and everything you need to learn Arduino from the ground up. We'll help you get started and at every step with top-notch instruction and our super-helpful course discussion space.