Menu
CoddyTech

Map to a Percent

Part of the Inputs section of Coddy's Arduino journey. Lesson 10 of 22.

Readings from 0 to 1023 mean little to a person. A percent from 0 to 100 is easier. map() converts a number from one range into another:

int percent = map(reading, 0, 1023, 0, 100);

It takes five numbers: the value, the low and high ends of its range, and the low and high ends of the new range. 0 becomes 0, 1023 becomes 100, and a value a quarter of the way along lands a quarter of the way along: 256 becomes 25.

map() works with whole numbers and drops any fraction, which is fine for a percent.

challenge icon

Challenge

Easy

The knob is on A0. Print how far it is turned, as a percent:

  • read A0
  • convert the reading to 0 to 100 with map()
  • print the percent, then wait 100 ms

Press Run, turn the knob, then Check.

Try it yourself

void setup() {
  Serial.begin(9600);
}

void loop() {
  int reading = analogRead(A0);
  // convert the reading to a percent with map(), print it, wait 100 ms
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Inputs

Practice on your own: Arduino playground