Pages: [1]   Go Down
Author Topic: Sine wave led fade in and out  (Read 1488 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 4
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
Logged

0
Offline Offline
Full Member
***
Karma: 0
Posts: 163
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
#define SINSIZE 255
#define TWOPIOVERSINSIZE    (PI*2)/(float)SINSIZE

#define LEDPIN 10
unsigned 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);
  }
  
}
Logged

0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 59
he's not a real doctor
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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....
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 4
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Pages: [1]   Go Up
Jump to: