map and constrain in Arduino
Rescale one range onto another, then clip the edges.
// map rescales one range onto another; constrain clips the edges.
const int KNOB_PIN = A1;
const int VENT_PIN = 6;
void setup() {
pinMode(VENT_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
int knob = analogRead(KNOB_PIN);
// 0-1023 counts onto 0-255 PWM, then clipped to a safe band.
int duty = map(knob, 0, 1023, 0, 255);
duty = constrain(duty, 20, 235);
analogWrite(VENT_PIN, duty);
Serial.println(duty);
delay(100);
}
How it works
map(knob, 0, 1023, 0, 255)moves counts onto PWM duty.constrain(duty, 20, 235)keeps the vent in its safe band.- Knob to vent in two library calls, no arithmetic by hand.
Keywords and builtins used here
OUTPUTSerialanalogReadanalogWritebeginconstconstraindelayintloopmappinModeprintlnsetupvoid
The run, in numbers
- Lines
- 18
- Characters to type
- 427
- Tokens
- 94
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in Analog, step 8 of 27 in Language basics.