A light that gets brighter and dimmer: analogWrite and map
Section 5: Sensors and numbersLesson 5.2 · ⏱ 9 min
analogWrite gives the LED a strength from 0 (off) to 255 (brightest), on the pins marked with ~ like 9.
The problem: the reading is from 0 to 1023, and the light from 0 to 255. The map command turns a number from one range into another.

📌 Another example: a light with four levels
analogWrite with four values: 0, then 85, then 170, then 255, and it repeats.


✍️ Practise
Build the changing light.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
✍️ Practise
The servo follows the potentiometer (map to 0~180).
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A steady dim light: the value 40.
👀 Show the solution🙈 Hide the solution


Result: dim.
Medium
The knob controls the light (map from 0–1023 to 0–255).
👀 Show the solution🙈 Hide the solution


Result: the more you turn the knob, the brighter the light.
Hard
Reversed: the knob at its start = the brightest light (map to 255–0).
👀 Show the solution🙈 Hide the solution


Result: it gets dimmer as you turn it.

