Keep Values in Range
Part of the Inputs section of Coddy's Arduino journey. Lesson 11 of 22.
Sometimes only part of a range should count. Say only the middle of the knob's travel matters, readings 200 to 800, and that should be 0 to 100 percent:
int percent = map(reading, 200, 800, 0, 100);That gives 0 at 200 and 100 at 800, but map() does not stop at the ends of the range. A reading of 0 gives -33, and 1023 gives 137. A percent below 0 or above 100 makes no sense.
constrain(x, low, high) keeps a number inside a range: anything below low becomes low, anything above high becomes high, and everything in between stays as it is.
percent = constrain(percent, 0, 100);Challenge
EasyThe knob is on A0. Print a percent where readings 200 to 800 count as 0 to 100:
- map the reading from 200 to 800 into 0 to 100
- keep it between 0 and 100 with
constrain() - print it, then wait 100 ms
Press Run, turn the knob all the way both ways, then Check.
Try it yourself
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(A0);
// map 200..800 to 0..100, keep it in 0..100, print it, wait 100 ms
}
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