Go Down

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

#### thezim

##### Jan 28, 2009, 03:30 am
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?

#### Fjornir

#1
##### Jan 28, 2009, 03:49 am
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 TWOPIOVERSINSIZE    (PI*2)/(float)SINSIZE#define LEDPIN 10unsigned char sins_of_our_fathers[SINSIZE];void setup(){  Serial.begin(9600);  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;    Serial.print(".");  }  Serial.println("Done.");}void loop(){  for(unsigned char i=0;i<SINSIZE;i++)  {    analogWrite(LEDPIN, sins_of_our_fathers[i]);    delay(50);    Serial.print("SIN: ");    Serial.println( sins_of_our_fathers[i] , DEC);  }    for(unsigned char i=0;i<255;i++)  {    analogWrite(LEDPIN, i);    delay(50);    Serial.print("NOTSIN: ");    Serial.println( i , DEC);  }  }`

#### drspectro

#2
##### Jan 29, 2009, 03:30 am
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....

#### thezim

#3
##### Jan 29, 2009, 03:40 am
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