Writing Arduino Code
Fade with PWM
13 minStudent plan
analogWrite, duty cycle as brightness, and using a for loop to fade an LED smoothly up and down.
After this lesson you can
- Fade an LED with analogWrite
- Explain how a digital pin fakes an analogue output
- Say why brightness does not look linear
A digital pin that pretends to be analogue
A digital pin has two states, so it cannot output 2.5 V. What it can do is switch between 0 V and 5 V so fast that the average is 2.5 V, high half the time.
That is pulse-width modulation. The switching happens around 490 Hz on most Arduino pins, far faster than the eye can follow, so an LED does not appear to flash; it appears dimmer.
analogWrite(pin, value) sets the duty cycle, where value runs from 0 to 255. 0 is always off, 255 is always on, 127 is roughly half brightness. The name is misleading, the pin is still purely digital, and only the ratio changes.
Only certain pins can do this: on an Uno they are 3, 5, 6, 9, 10 and 11, and they are marked with a ~ on the board.
In the full lesson
- A digital pin that pretends to be analogue
- Fading with a loop
- Brightness is not linear
This lesson comes with the Student plan. The first module of Programming is free.