I have searched for an easy example for a fade program using PWM and the Sine function. After realizing there wasn't a simple one, I did what all of us do... and "make" one. I call this one SineFade and it creates an extremely smooth breathing effect. More so, than other fade programs I have tried. The current fade programs just count in a linear fashion, up and down. This example uses the Sine function and one PWM pin.
Fritzing diagram:
Schematic:
Note: I have added the serial output that works nicely with the "Serial Monitor" in the Arduino IDE.
See this code at work: SineFade - Short clip of Arduino Beetlle running with Serial Plotter - YouTube
/*
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
This project is posted at: https://forum.arduino.cc/index.php?topic=625662.0
Project inspired by post at: https://forum.arduino.cc/index.php?topic=27475.0
*/
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.
Serial.begin(9600); // Initiates serial communication
}
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.
Serial.println(brightness); // "Serial Monitor" or "Serial Plotter" information.
delay(15); // Delay between each point of sine wave.
}
}
SineFade.ino (2.51 KB)