Go Down

Topic: Sine wave led fade in and out (Read 3308 times) previous topic - next topic


So just got my Arduino and have been learning the ropes. I got to fading LEDs and wondered how one would fade it using a sine wave vs the normal triangle wave in the example. I've seen an example for fading multiple LEDs using a sine wave table and I understand the table usage but how would one generate the table?


Declare an array the size you want, then walk through the array computing the sine of that position, storing it in the array. I've got code handy that does this anyways for my synthesizer and I was curious just how different a PWM driven LED would would look if it was driven by a sine wave than if it was driven by a simple for() loop.

Conclusion: not worth the effort to write the code but if you're still interested here you go.

Code: [Select]

#define SINSIZE 255

#define LEDPIN 10
unsigned char sins_of_our_fathers[SINSIZE];

void setup()
 pinMode(10, HIGH);

 Serial.print("Precomputing sine wave.");
 for(unsigned char i=0;i<SINSIZE;i++)
   sins_of_our_fathers[i] = (128.0*sin( (float)i*TWOPIOVERSINSIZE) ) + 127;

void loop()
 for(unsigned char i=0;i<SINSIZE;i++)
   analogWrite(LEDPIN, sins_of_our_fathers[i]);
   Serial.print("SIN: ");
   Serial.println( sins_of_our_fathers[i] , DEC);
 for(unsigned char i=0;i<255;i++)
   analogWrite(LEDPIN, i);
   Serial.print("NOTSIN: ");
   Serial.println( i , DEC);


Not sure if you want a sine wave specifically or just a nice looking fade in fade out on the LED.

Something that makes a convincing LED fade is a fibonacci sequence of delays.  1 2 3 5 8 13 21 etc.  Then multiply by your minimum delay when you build your table.

As the LED gets brighter you need a larget step to make a detectible difference anyway.  The Fibonacci sequence acts a lot like a log scale, but it is much faster to compute your table.  I suspect a sine is going to seem like full bright 1/3 of the time and full dark 1/3 of the time....


I'd like to apply it to other things besides an LED. If nothing else to better my general knowledge. By trade I'm a C# developer but have never had to dip into some of the trig stuff like this but I can see it usefulness in things.

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131