Info
Content

Arduino PWM Exponential LED Fading

 

Light perception is logaritmic so we need exponential curve for having a linear light fading

const int outputPin = 9;
const int pwmMaxRes = 255;

// The R value in the graph equation
float R;

void setup() {
  // set the pin connected to the LED as an output
  pinMode(outputPin, OUTPUT);

  // Calculate the R variable (only needs to be done once at setup)
  R = (pwmMaxRes * log10(2))/(log10(pwmMaxRes));
}

void loop() {
  int brightness = 0;

  for (int i = 0; i <= pwmMaxRes; i++) {
      // Calculate the required PWM value for this interval step
      brightness = pow (2, (i / R)) - 1;
      // Set the LED output to the calculated brightness
      analogWrite(outputPin, brightness);
      delay(40);
  }
}
No Comments
Back to top