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.

Let’s use an example that involves a potentiometer and an electrical motor.

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.

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.

We publish fresh content each week. Read how-to's on Arduino, ESP32, KiCad, Node-RED, drones and more. Listen to interviews. Learn about new tech with our comprehensive reviews. Get discount offers for our courses and books. Interact with our community. One email per week, no spam; unsubscribe at any time

Image
{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}