Breathing LED, PWM - Change duration of breath

Hi Guys and Girls,

In developing a breathing lamp project of mine, I've discovered Jeremy Saglimbeni's Breathing Light code which mimics fading that of a Mac sleep light.

My comprehension of code at this stage is quite modest, so I'm struggling to understand how to change the total duration of this fade to two minutes for example.

The original code is as follows.

/*
"Breathing sleep LED, like on a Mac.
Jeremy Saglimbeni 2011
thecustomgeek.com

LED is attached to pin 11 in series with a 5.6K resistor
*/
int i = 0;
void setup() { // bring the LED up nicely from being off
  for(i = 0 ; i <= 15; i+=1)
  {
    analogWrite(11, i);
    delay(5);
  }
}
void loop()
{
  for(i = 15 ; i <= 255; i+=1)
  { 
    analogWrite(11, i);
    if (i > 150) {
      delay(4);
    }
    if ((i > 125) && (i < 151)) {
      delay(5);
    }
    if (( i > 100) && (i < 126)) {
      delay(7);
    }
    if (( i > 75) && (i < 101)) {
      delay(10);
    }
    if (( i > 50) && (i < 76)) {
      delay(14);
    }
    if (( i > 25) && (i < 51)) {
      delay(18);
    }
    if (( i > 1) && (i < 26)) {
      delay(19);
    }
  }
  for(i = 255; i >=15; i-=1)
  {
    analogWrite(11, i);
    if (i > 150) {
      delay(4);
    }
    if ((i > 125) && (i < 151)) {
      delay(5);
    }
    if (( i > 100) && (i < 126)) {
      delay(7);
    }
    if (( i > 75) && (i < 101)) {
      delay(10);
    }
    if (( i > 50) && (i < 76)) {
      delay(14);
    }
    if (( i > 25) && (i < 51)) {
      delay(18);
    }
    if (( i > 1) && (i < 26)) {
      delay(19);
    }
  }
  delay(970);
}

Any help you can shed would be brilliant!

Thank you in advance!

  • Daniel

What you need to do is to work it through step by step using paper and pen.

Mark

How long does the original code take to run 1 cycle? Looks about 10 seconds to me, but you have it set-up and can time it.
Divide 120 (= 2 minutes) by the number of seconds it takes, then multiply ALL the delays by the result (whole numbers only). That should give you a cycle of ~2 minutes.

That's perfect, thank you Henry - you are the best! :open_mouth:

Simple mathematics. A Karma point would be appreciated.

I would consider using functions explicitly instead of using all of this code. Using functions will also smooth out some of the perceived jumps in brightness as well. Here is an example of a smooth PWM pulse that emulates a breathing LED:

I wrote an entire blog on different breathing functions - where you can explore how to alter different parameters such as length of pulse, etc. Here's the link, if you're interested:

Arduino Breathing LED Functions