Sub topic 10
Making fades look even with gamma correction
This chapter explains why a fade that steps evenly in analogWrite() values looks uneven to the eye, and how to fix it with a gamma curve. It assumes you have read the earlier chapters of this tutorial. You should be comfortable with duty cycle, analogWrite() with its 0 to 255 range, an LED wired through a current-limiting resistor to a PWM pin, and a millis()-based fade loop. You also need to know basic C++ arrays and for loops.
The problem: even steps do not look even
Suppose you fade an LED with analogWrite() and step the value by 1 every few milliseconds. The code is correct, but the result looks wrong. The LED seems to brighten quickly near the dark end. Around the top of the range it seems to stall, because values from about 200 to 255 look almost the same.
Two facts explain this:
- The LED's light output is roughly proportional to its average current. A PWM duty cycle of 50% gives about half the average current, so about half the light. Doubling the
analogWrite()value doubles the physical light output. - The eye does not respond in proportion to light output. Perceived brightness grows much more slowly than physical luminance. A common model is a power law with an exponent between about 0.33 and 0.5. Going from 1% to 2% of full light output looks like a large jump. Going from 90% to 91% looks like nothing.
A linear ramp of duty values is therefore a very uneven ramp of perceived brightness. Gamma correction compensates for this by applying a power curve to the level before it reaches analogWrite().
The fade logic works in perceptual space, where equal steps look equal. The gamma curve converts that level into the duty value the hardware needs.
The gamma formula
For a level from 0 to 255, the corrected duty value is:
duty = 255 * (level / 255) ^ gammaThe level is first scaled to 0.0 to 1.0. It is raised to the power gamma, then scaled back to 0 to 255. The endpoints are unchanged: 0 stays 0 and 255 stays 255. The middle of the range is pushed down, so low levels get small duty values and the eye sees a more gradual start.
A gamma of 2.2 is the usual starting point. It matches the standard used by most displays. Many LED projects use values between 2.2 and 2.8, and the best value depends on the LED, any diffuser, and the room lighting. Treat gamma as a number you tune by eye.
| Level | Duty at gamma 2.2 | Duty as a percent of full |
|---|---|---|
| 0 | 0 | 0% |
| 16 | 1 | 0.4% |
| 32 | 3 | 1.2% |
| 64 | 12 | 4.7% |
| 128 | 56 | 22% |
| 192 | 137 | 54% |
| 255 | 255 | 100% |
Level 128 is the middle of the range, but its duty is only 56, about 22% of full. At that duty the LED looks roughly half as bright as at full power. This is why a plain analogWrite(pin, 128) looks brighter than people expect from "50%".
Seeing the difference with two LEDs
The most convincing way to learn this is to compare. Wire two LEDs, each with its own resistor (for example 220 ohms), to pins 9 and 10 of an Uno. Both pins are driven by the same timer, so they run at the same PWM frequency. The sketch below fades both with the same level counter. The LED on pin 9 gets the raw level and the LED on pin 10 gets the gamma-corrected level.
const uint8_t LINEAR_LED_PIN = 9;
const uint8_t GAMMA_LED_PIN = 10;
const float GAMMA = 2.2;
uint8_t gammaCorrect(uint8_t level) {
float normalized = level / 255.0;
return (uint8_t)(pow(normalized, GAMMA) * 255.0 + 0.5);
}
int level = 0;
int step = 1;
void setup() {
pinMode(LINEAR_LED_PIN, OUTPUT);
pinMode(GAMMA_LED_PIN, OUTPUT);
}
void loop() {
analogWrite(LINEAR_LED_PIN, level);
analogWrite(GAMMA_LED_PIN, gammaCorrect(level));
if (level + step < 0 || level + step > 255) {
step = -step;
}
level += step;
delay(8);
}Watch both LEDs. The linear one rushes through its dim range, then seems to sit at full brightness for the last third of the ramp. The gamma one starts slowly and keeps changing visibly until the end. Both complete a cycle in the same time.
Two details in gammaCorrect() matter:
level / 255.0uses a floating-point literal. Writinglevel / 255would be integer division, which is 0 for every level below 255. The whole fade would then stay dark until the last step.+ 0.5before the cast rounds to the nearest integer. A plain cast touint8_ttruncates, which makes the low end darker than the formula intends.
Precomputing a lookup table
The gamma curve depends only on the level, and there are only 256 levels. You can compute all 256 results once, store them in an array, and replace each pow() call with an array read. This is faster and keeps the timing of loop() predictable.
The sketch below combines the table with the millis() scheduling from the previous chapter. The fade advances every 8 ms and loop() stays free for other work.
const uint8_t LED_PIN = 9;
const float GAMMA = 2.2;
const unsigned long INTERVAL_MS = 8;
uint8_t gammaTable[256];
unsigned long lastStepTime = 0;
int level = 0;
int step = 1;
void setup() {
pinMode(LED_PIN, OUTPUT);
for (int i = 0; i < 256; i++) {
gammaTable[i] = (uint8_t)(pow(i / 255.0, GAMMA) * 255.0 + 0.5);
}
}
void loop() {
unsigned long now = millis();
if (now - lastStepTime >= INTERVAL_MS) {
lastStepTime = now;
analogWrite(LED_PIN, gammaTable[level]);
if (level + step < 0 || level + step > 255) {
step = -step;
}
level += step;
}
// Other work can run here on every pass through loop()
}The table costs 256 bytes of SRAM. An Uno has 2048 bytes in total, so this is noticeable but affordable. If SRAM is tight, you can store a precomputed table in flash with PROGMEM and read it with pgm_read_byte(). That needs a table literal of 256 numbers, which you generate once on a computer or with a sketch that prints the values.
The same table works for the potentiometer sketch from earlier. Replace analogWrite(LED_PIN, reading >> 2) with analogWrite(LED_PIN, gammaTable[reading >> 2]). The knob then feels much more natural, because turning it a quarter of the way gives a quarter of the perceived brightness, not a nearly full-bright LED.
Edge cases and limits
Lost resolution at the dark end
Gamma correction maps 256 inputs onto 256 outputs, but it compresses the dark end. With gamma 2.2 and rounding, roughly the first 15 input levels all map to duty 0. Levels 15 to 30 or so map to duty values of only 1, 2 and 3. The result is that the LED stays off for the first part of the fade, then jumps to the dimmest visible step. At gamma 2.8 the dead zone grows to roughly the first 28 levels.
At low brightness, each duty step is a large relative change. Going from duty 1 to duty 2 doubles the light output. The eye sees this as a visible step even when the gamma curve is correct. This is called banding.
You have three practical options:
- Accept it. For status lights and simple effects this is usually fine.
- Lower the gamma, for example to 2.0, to shrink the dead zone and soften the steps.
- Use more PWM resolution. The ATmega328P's Timer1 can run in a 16-bit mode, which gives thousands of duty steps. This is outside the reach of
analogWrite(), which always uses 8 bits. It needs direct timer register code or a library.
Gamma is a model, not a law
The 2.2 figure comes from display standards. It is a reasonable approximation of human lightness perception, but it is not exact. LED color, ambient light, diffusers, and the viewer's eyes all change how a fade looks. A fade viewed in a dark room needs a different curve from one viewed in daylight. Tune the value by looking at the LED.
Gamma changes the effective fade timing
With a linear ramp, the fade spends most of its time at brightness levels the eye cannot distinguish. With gamma, the visible change is spread across the whole ramp, so the fade looks longer even though the timing is the same. If you want a particular visible duration, adjust INTERVAL_MS after applying gamma.
Do not correct twice
Apply gamma once, at the last step before analogWrite(). If you feed an already corrected value back into the fade logic, or apply the curve to the potentiometer reading and then again to the output, the result is too dark and the dead zone grows.
Choosing gamma: a short procedure
- Start with
GAMMA = 2.2. - Run the two-LED comparison sketch in the lighting conditions you care about.
- If the corrected LED still looks like it rushes through its dim range, increase gamma in steps of 0.2.
- If the LED stays off too long at the start, or the first visible step is a big jump, decrease gamma.
- Settle on a value, then put it in a named constant so you can change it in one place.
Exercise
Using gamma 2.2, the formula duty = 255 * (level / 255) ^ 2.2, and rounding to the nearest integer, what duty value does a level of 128 produce? What percent of full duty is that, and why does the LED still look roughly half as bright as at full power?
Show answer
A level of 128 gives (128 / 255) ^ 2.2 ≈ 0.219, and 0.219 * 255 ≈ 56. That is about 22% of full duty. The LED emits about 22% of its full light output, but the eye perceives brightness on a compressed scale, much closer to a square-root or cube-root relationship with light output than to a straight proportion. A light output of about 22% therefore looks close to half as bright.
Exercise
A fade using a 256-entry gamma 2.8 table seems to keep the LED fully off for the first second of the fade and then jump on. What causes this, and name two ways to reduce it?
Show answer
At gamma 2.8 the first roughly 28 input levels round to a duty of 0, so the LED stays off while the level counter climbs through them. The next levels give duty values of only 1 or 2, which are large relative jumps. To reduce it, lower the gamma (for example to 2.2), or start the level counter at the first level that gives a non-zero duty. A third option is to use 16-bit PWM from Timer1 so that the dark end has finer duty steps.