I am trying to make a simple breathing led circuit in which the intensity of the led varies between 0 and 255. I followed the Fade tutorial on the Arduino site, which gives me what I want, but I notice that the change in brightness is much more noticeable when the intensity is at 0.
In other words, the brightness seems to be bouncing back from 0, rather than slowly gliding back up.
I tried mapping the value of the delay to brightness: del = map(brightness, 0, 255, 10, 1);
but that did not do the job.
The mapping seems to work better when I use 30 instead of 10 as longest delay time: del = map(brightness, 0, 255, 30, 1);
but I think what I really need is to implement some sort of sinusoidal function to make transitions smoother, but I am really struggling with the math... Any suggestions?
Here is the code:
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 1; // how many points to fade the LED by
int del;
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
// here I map the delay to brightness
del = map(brightness, 0, 255, 10, 1);
delay(del);
}