PWM Exponential LED Fading on Arduino (or other platforms)
For a project I am working on I needed to dim a LED strip light using the PWM (pulse width modulated) outputs on an Arduino. The most straightforward way to do this would have been to linearly vary the output frequency. Shown below in an Arduino sketch:
// Use pin 9 as the PWM output
const int outputPin = 9;
void setup() {
// Set the pin as a digital output
pinMode(outputPin, OUTPUT);
}
void loop() {
// Fade the brightness from 0 (min) to 255 (max) with 40ms delay per step
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(outputPin, brightness);
delay(40);
}
}
However the light outputted by the LED does not scale linearly. If you were to use the very scientific metric of “Perceived Brightness” vs. time for the above sketch it would look something like the below for a linear PWM signal:
…