An LED controlled by a knob: map
Section 11: Smart systemsLesson 11.1 · ⏱ 7 min
map(v, 0, 1023, 0, 255) turns the number from one range into another. And analogWrite gives the LED a strength from 0 to 255 on a pin marked with ~.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int v = analogRead(A0);
int b = map(v, 0, 1023, 0, 255);
analogWrite(9, b);
}


🖥️ What happens on the stage?
We ran this code in Robo Maker and the challenge passed: “Bravo! It works”.
📌 Another example: an LED with three levels
Instead of map: three fixed levels depending on where the knob is.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int v = analogRead(A0);
if (v < 341) {
analogWrite(9, 0);
} else if (v < 682) {
analogWrite(9, 100);
} else {
analogWrite(9, 255);
}
}



✍️ Practise
Make the LED that gets brighter and dimmer.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Reversed: the knob at its start = the brightest light.
👀 Show the solution🙈 Hide the solution
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int v = analogRead(A0);
analogWrite(9, map(v, 0, 1023, 255, 0));
}

Result: it gets dimmer as you turn the knob.
Medium
A minimum: the LED never goes off (map to 40–255).
👀 Show the solution🙈 Hide the solution
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int v = analogRead(A0);
analogWrite(9, map(v, 0, 1023, 40, 255));
}

Result: even at zero it stays dimly on.
Hard
The knob controls the blinking speed.
👀 Show the solution🙈 Hide the solution
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int v = analogRead(A0);
int t = map(v, 0, 1023, 100, 1000);
digitalWrite(9, HIGH);
delay(t);
digitalWrite(9, LOW);
delay(t);
}

Result: small knob = fast blinking.

