Who has not happened to note that wonderful breathing led effect present on some electronic devices?
There are makers all over the world equipped with oscilloscope tried to do reverse engingering to find the algorithm and turn it into an Arduino sketch. The problem lies in the fact that most of the codes found in the network have two defects: the first is that such algorithms do not contain a function but a series of pre-calculated values that do not make the effect smooth, while the second resides in the fact that often these codes are blocking, making use of delay and therefore do not permit the correct execution of the remaining code inside of the sketch.
Ispired by the Sean Voisen’s post who find the function defining the PWM values to drive the LED, I made some changes and tests to make it non-blocking and to make it work in background allowing execution to other code.
The end result is the following:
The connection is obviously as for any other LEDs and the system is capable of driving even power LEDs or LED strip, through appropriate transistor or MOSFET (See: Driving a LED Strip with Arduino)
The Arduino code is the following:
/* NonBlockingBreathingLed 0.1 by Luca Soltoggio - 2015 12 May 2015 http://www.arduinoelettronica.com/ https://arduinoelectronics.wordpress.com/ http://minibianpi.wodpress.com/ Use a exp + sin function to recreate a non-blocking breathing led effect Released under GPL v.2 license */ #include <math.h> #define ledPin 11 int i=0; int breathe_delay = 15; // delay between loops unsigned long breathe_time = millis(); void setup() { } void loop() { nonBlockingBreath(); // call the nonblocking function // yourOtherCodeHere(); } void nonBlockingBreath() { if( (breathe_time + breathe_delay) < millis() ){ breathe_time = millis(); float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0; // this is the math function recreating the effect analogWrite(ledPin, val); // PWM i=i+1; } }
Have fun!!! 🙂