SineFade - Extremely simple LED fade using a PWM pin and Sine function

And the code that @stievenart missed posting

/*

  SignFade

  This is a very simple example showing how to smoothly fade a LED using the Sine function and a PWM
  pin. I have seen many complex and confusing examples. And, I felt that a simple version was needed.
  This code was written by Greg Stievenart with no claim to the information provided in this code.
  Please feel free to copy, modify and share. Freely published July 8, 2019

  PWM is broken into a resolution of 255 units. The units in this example are broken down into an
  imaginary circle with a radius of 255 divided by 2. This number is multiplied by the Sine of
  the wave.

  EXAMPLE:

   255/2       **                      **                      **                        **
            *      *                *      *                *      *                  *      *
          *          *            *          *            *          *              *          *
       0 * ---------- * -------- * ---------- * -------- * ---------- * ---------- * ---------- *
                       *        *              *        *              *          * 
                         *    *                  *    *                  *      *
  -255/2                   **                      **                       **

  More information about the Sine fuction: https://en.wikipedia.org/wiki/Sine
  
*/

int led = 9;                                              // The PWM pin the for the LED.
int brightness = 0;                                       // LED brightness.

void setup(){
  
  pinMode(led, OUTPUT);                                   // Pinout set to pin 9.
}

void loop(){                                              // Main loop

  for (int i = 0; i < 360; i++){                          // 360 degrees of an imaginary circle.
    
    float angle = radians(i);                             // Converts degrees to radians.
    brightness = (255 / 2) + (255 / 2) * sin(angle);      // Generates points on a sign wave.
    analogWrite(led,brightness);                          // Sends sine wave information to pin 9.
    delay(15);                                            // Delay between each point of sine wave.
  }
}
1 Like