Zach Christensen
arduino journey
P05Timing and BrightnessSession 5✓ Working

PWM Fade

A pin that only does 0 V or 5 V, made to look like it does everything in between.

Running

The sketch

05_PWM_Fade.ino
// P05 - PWM Fade (blocking version)// LED smoothly brightens and dims using analogWrite().const uint8_t PIN_LED = 9;void setup() {  pinMode(PIN_LED, OUTPUT);}void loop () {  for (int duty = 0; duty <= 255; duty++) { // fade up    analogWrite(PIN_LED, duty);    delay(8);  }  for (int duty = 255; duty >= 0; duty--) { // fade down    analogWrite(PIN_LED, duty);    delay(8);  }}

Same LED and the same 220 Ω on D9 as External LED. Nothing rewired. analogWrite instead of digitalWrite, a counter running 0 to 255 and back, 8ms a step. A full sweep is 2 × 256 × 8, so about 4.1 seconds.

The LED is never dim

It is fully on or fully off the entire time. There is no in between at the LED, and no pin on this board can output 3 V.

What changes is the fraction of each period the pin spends HIGH, which is the duty cycle. On D9 that switching happens at about 490 Hz, far faster than a photoreceptor resolves, so the eye adds it up and calls the result a brightness. The dimming happens in my retina, not on the breadboard.

That also decides where PWM works and where it does not. It needs something downstream that averages. The eye averages light, a motor's mass averages torque, a speaker cone averages pressure. No averager, no analog behaviour. A multimeter is an averager too, which is why it reads 2.51 V at duty 128 instead of flicking between 0 and 5.

What I learned