انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Maker: home
0. Lab tour1
1. The start: the Arduino6
2. Wiring and the traffic light4
3. Inputs: the button4
4. Sound and movement5
5. Sensors and numbers5
6. Distance, the screen and colours5
7. Motors and the car4
8. The project: the city's smart gate3
9. From blocks to C++ code5
10. Sensors and screens in code5
11. Smart systems5
12. Bluetooth: control from the phone1

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 ~.

⚙️ The knob controls how bright the light is
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  int v = analogRead(A0);
  int b = map(v, 0, 1023, 0, 255);
  analogWrite(9, b);
}
The knob a little: dim light
The knob a little: dim light
The knob all the way: bright light
The knob all the way: bright light
🖥️ 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.

⚙️ An LED with three levels
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);
  }
}
Off
Off
Medium
Medium
Bright
Bright
✍️ Practise
Make the LED that gets brighter and dimmer.
✍️ Practise here in the lessonor open the lab in a new page ↗

🎯 Challenge yourself

Easy

Reversed: the knob at its start = the brightest light.

👀 Show the solution
⚙️ Solution
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  int v = analogRead(A0);
  analogWrite(9, map(v, 0, 1023, 255, 0));
}
In the lab
In the lab

Result: it gets dimmer as you turn the knob.

Medium

A minimum: the LED never goes off (map to 40–255).

👀 Show the solution
⚙️ Solution
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  int v = analogRead(A0);
  analogWrite(9, map(v, 0, 1023, 40, 255));
}
In the lab
In the lab

Result: even at zero it stays dimly on.

Hard

The knob controls the blinking speed.

👀 Show the solution
⚙️ 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);
}
In the lab
In the lab

Result: small knob = fast blinking.

Finished the lesson? Mark it so your progress counts.