Fade the pin-13 lamp
A fade that raises the duty in equal steps does not look even: it leaps up at the start and crawls at the end, because the eye judges dim light far more finely than bright. A power curve fixes it. The pin-13 lamp has no PWM pin behind it, so this fade is software PWM on D13, and the same curve works with analogWrite on any ~ pin.
PWM by hand on D13
The L lamp follows D13, and D13 has no timer, so analogWrite cannot dim
it. The sketch does the timer's job in loop(): a period of 4096 µs is split
into 256 slices of 16 µs, and the lamp is on for the first level slices of
each period. That is PWM at 244 Hz with 256 levels, fast enough not to flicker.
micros() on a 16 MHz board counts in steps of 4 µs, which is why a slice
is 16 µs and not 1. And the period is a power of two for a reason: micros()
wraps round after about 70 minutes, and 2³² divides evenly by 4096, so the
wrap does not break a period.
Two levels are special. 0 never switches on, and 255 is forced fully on
rather than on for 255 slices of 256, the same promise analogWrite makes on
a ~ pin, where 0 and 255 become a plain LOW and HIGH.
Equal steps do not look equal
The orange line is the obvious fade: step 20 of 100 gets 20% duty. The eye does not see 20% of the light as 20% of the brightness; it sees something nearer half. So a straight-line fade jumps up in its first few steps and then crawls, and the top half looks like nothing is happening.
The fix is to spend the early steps on very small duties. The sketch raises each step to the power 2.2 before turning it into a duty, a common choice for LEDs and close to the one screens use, called gamma:
float x = step / 100.0; // 0.0 to 1.0, how far through
x = pow(x, 2.2); // the eye's curve, undone
byte duty = x * 255 + 0.5; // 0 to 255, roundedStep 20 now gets 7 of 255, step 50 gets 55, and step 100 still gets 255. The swatches are illustrative: brightness as eyes judge it varies with the lamp and the room, and 2.2 is a good starting point rather than a law.
The same fade on a ~ pin
With an LED and resistor on ~9, the timer does the switching and the sketch
only sets the level, with no micros() arithmetic and no stutter when it
prints:
for (int s = 0; s <= 100; s++) {
analogWrite(9, pow(s / 100.0, 2.2) * 255 + 0.5);
delay(20);
}The curve is the part that carries over. Any fade a person watches, on any pin and any board, looks better through it.
The code
No wiring. The pin-13 lamp (L on the UNO, D13 on the Nano) fades up and down in two seconds each way, once with the duty rising in a straight line and once along the corrected curve, and the Serial Monitor says which is which.
// Fade_D13_Gamma.ino — fade the pin-13 lamp, linear then
// corrected, in turn
// Tools > Board: Arduino Uno, or Arduino Nano with
// Processor ATmega328P (Old Bootloader if the upload says
// "not in sync")
// Tools > Port: the CH340 port
// Serial Monitor: 9600 baud
// Wiring: none. The lamp is L on the UNO, D13 on the Nano.
// D13 has no PWM timer, so this is PWM in software:
// 256 levels of 16 us, a 4096 us period, 244 times a second.
const byte LAMP = 13;
const unsigned int TICK_US = 16;
const unsigned long PERIOD_US = 256UL * TICK_US;
const unsigned int STEP_MS = 20; // 100 steps up takes 2 s
int step = 0; // 0 to 100, how far through the fade
int dir = 1;
bool corrected = false;
byte level = 0; // 0 to 255, the duty actually used
unsigned long lastStep = 0;
byte dutyFor(int s) {
float x = s / 100.0;
if (corrected) x = pow(x, 2.2); // the eye's curve, undone
return (byte)(x * 255 + 0.5);
}
void setup() {
pinMode(LAMP, OUTPUT);
Serial.begin(9600);
Serial.println("linear");
}
void loop() {
// 2^32 is a multiple of 4096, so this survives micros() wrapping.
unsigned long into = micros() % PERIOD_US;
bool on = level == 255 || into < (unsigned long)level * TICK_US;
digitalWrite(LAMP, on ? HIGH : LOW);
if (millis() - lastStep >= STEP_MS) {
lastStep = millis();
step += dir;
if (step >= 100) dir = -1;
if (step <= 0) {
dir = 1;
corrected = !corrected;
Serial.println(corrected ? "corrected (gamma 2.2)" : "linear");
}
level = dutyFor(step);
}
}The linear fade looks bright almost at once and spends most of its time barely changing. The corrected one looks like a steady climb. Both start fully off and end fully on.
When it does not work
The curve's first few steps all round to duty 0 or 1 of 255, so the dimmest end has only a handful of real levels. That is the limit of 256 levels, not a bug. More levels need a longer period or a faster timer.
Software PWM is the loop itself. While Serial.print or a delay holds the loop, D13 stays where it was. This sketch only prints when the fade changes mode; a fade on a ~ pin with analogWrite has no such problem, because a timer does the switching.
The shortest pulses here are 16 µs, under 1% of the period, and a lamp lit that briefly is barely lit at all. On the UNO it is dimmer still: L is driven through an LM358 buffer that is not instantaneous, so very short pulses come out weaker than their width suggests. The Nano drives its D13 lamp from the pin directly. The middle and top of the fade are unaffected.
13 is not a ~ pin. analogWrite there gives only LOW below 128 and HIGH from 128. That is why this sketch switches D13 itself with micros().
What happens to the ~ pins when a sketch also plays a tone or drives a servo.
tone(), Servo and the timers they take →Edit this page — content/books/atmega328p/fade-an-led.mdx
Discuss this article
Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.