firefly night light

I've written a program to "look" like fireflies blinking in my kid's room. It's a pretty simple program and I had a little help, but it works pretty well. I thought I'd share with anyone who enjoys seeing them in the summer. They started coming out about a week ago in central Indiana. have fun.
I used the PWM outputs and a cosine function to vary the duty cycle for a smooth increase and decrease in brightness.

/*This sketch is intended to approximate the blinking of fireflies.  It varies the delay between
blinks and varies the total blink time.  I've used the random() function to vary which PWM  output
is chosen for the next blink.
Hope you get some enjoyment out of it.  I created it as a fun night light for my kids.
Chad Richardson -- Chad@ChadsCustomWood.net
*/


int value;
int pwmPin = 11;                    // light connected to digital pin 11-- I just chose an initial value
//int ledpin2 = 9;
long time=0;
int period = 500;
int i = 0;
long blink_delay = 1000;            // these must be declared as long due to the random() operation
long blink = 3;
long random_led = 55;
const byte pwmPins [] = {3, 5, 6, 9, 10, 11};

void setup()
{                                    //nothing to setup
}

void loop()
{
  choose_firefly();
  fade();

  blink_delay = random(500, 4001);
  delay(blink_delay);  
  blink = random(2, 5);  
  
}
void fade()
{
  for(i=0; i<255;)
  {
    time = i;
    value = abs(-127+127*cos(4*PI/period*i));            //the -127 value shifts the cosine curve negative with a zero initial value; abs shifts everything positive
    analogWrite(pwmPin, value);           // sets the value (range from 0 to 255)
    delay(blink);
    i++;
  }
}

void choose_firefly()
  {
    pwmPin = pwmPins [random (0, 6)];   
  }

How about some video so we can see what you have done?

Here's the video. Please give me your comments.

Ahh I see what you've done now. Neat. Are you going to put a little circuit and the LED's into a jar or something like that?

I'm doing something very similar, fading LEDs on my ceiling to emulate a twinkling star field. You're using almost the same logic I am for picking a random LED, and fading it up and down. :slight_smile:

I haven't decided exactly what the end result should look like. The bugs in a jar is good, and I've seen some video of it. I had also thought of getting a small sheet of wood or something and then putting the LEDs through holes in that. I'll post some more pictures and/or video when I've figured it out.

I was just brain storming and thought of a way to use all of the outputs on my Arduino for fire flies. I could use one PWM output to control the fade rate of the LED. All other outputs would be tied to transistors and LEDs. I would wire them as common Anode so that I could light any one of 19 fire flies, instead of only 6. Basically, I'd be multiplexing the outputs.

Remember you can use software PWM to give you PWM on all of your digital outputs. Also remember that analog pins 0 to 5 can also be used as digital pins too.

If you want to go really wild, you could control, say, 96 LEDs, 6 at a time, by connecting the PWM outputs to 74HC154s, and addressing them with 4 digital pins.

Or wire them as a matrix, and use a single HC154 to control the high-side drivers.

Ran

Or use 74HC595's and daisy chain as many as you like. You get 8 LED's per IC.

Do you know anyway of making the code randomly light these up but not one after another? It would be even more realistic if they lit up more sporadically without letting the last one fade to black.

I've been struggling with a code for this. Being untrained in the ways of Arduino doesn't help. :-[

There is a call to randomly choose which LED to light. There is also a call to randomly choose how long to wait between blinks (from 1/2 second to 4 seconds). Another call chooses how long the blink will last--this is the blink value. It will wait for a few milliseconds between incrementing the time "i".

You can play around with any of these values to get the affect you want. If you don't want a fade to black between the two values, you can change the blink delay value to 0. They would immediately light one after another. Does this answer your question?

I think he want to be able to fade x number of leds at the same time, in case the fireflies are not polite enought to wait for the previous to be done.

I think you ought to create a Firefly struct, like so:
[COMPLETELY UNTESTED, BUT COMPILING CODE]

#include <TimedAction.h>
/*
Settings
*/
const byte MAX_FADE_INCREMENT = 5;
const byte MIN_FADE_INCREMENT = 2;
const byte TICK_FREQUENCY = 5;
const byte ALIVE_PROBABILITY = 50; //in percent e.g 50 = 50%

/*
Setup the TimedActions
*/
TimedAction randomizeAction = TimedAction(500,randomizeFlies);
TimedAction tickAction = TimedAction(TICK_FREQUENCY,tickFlies);

/*
Prepare the data needed for controlling the 'fireflies'
*/
//keep track of the state of the firefly
typedef enum {
  OFF, FADE_IN, FADE_OUT
} FireflyState;
//store data regarding an individual flie
typedef struct ff {
  byte id;
  FireflyState state;
  byte fadeValue;
  byte fadeSpeed;
} Firefly;

//prepare the flies
const byte NUMBER_OF_FLIES = 6;
Firefly flies[] = {
  { 3,  OFF, 0, MIN_FADE_INCREMENT },
  { 5,  OFF, 0, MIN_FADE_INCREMENT },
  { 6,  OFF, 0, MIN_FADE_INCREMENT },
  { 9,  OFF, 0, MIN_FADE_INCREMENT },
  { 10, OFF, 0, MIN_FADE_INCREMENT },
  { 11, OFF, 0, MIN_FADE_INCREMENT }
};

void setup(){
  //seedRandom( analogRead(0) );
}

void loop(){
  randomizeAction.check();  //is it time to randomize the flies?
  tickAction.check();      //fade each flie
}

/*
Implement your own logic if you use shift register, multi-/charlieplexing etc etc
This implementation assumes flie == pin with PWM capabilities
*/
void setFlie(byte flie, byte fade){
  analogWrite(flie,fade);
}

void randomizeFlies(){
  for (byte i=0; i<NUMBER_OF_FLIES; i++){    //loop through all flies
    if (flies[i].state == OFF){      //if the flie is in OFF state
      if (random(0,100)<=ALIVE_PROBABILITY){ //randomize state
        flies[i].state = FADE_IN;
        flies[i].fadeSpeed = random(MIN_FADE_INCREMENT,MAX_FADE_INCREMENT);
      }//else keep state
    }
  }
  randomizeAction.setInterval( random(500,4000) ); //decide when to randomize again
}

void tickFlies(){
  for (byte i=0; i<NUMBER_OF_FLIES; i++){    //loop through all flies
    //set fade value
    switch (flies[i].state){
      case FADE_IN:
        flies[i].fadeValue += flies[i].fadeSpeed;
        if (flies[i].fadeValue >= 255) { flies[i].state = FADE_OUT; }
        else { setFlie( flies[i].id, flies[i].fadeValue ); }
      break;
      case FADE_OUT:
        flies[i].fadeValue -= flies[i].fadeSpeed;
        if (flies[i].fadeValue < 0) { flies[i].state = OFF; }
        else { setFlie( flies[i].id, flies[i].fadeValue ); }
      break;
    }
  }
}

The thought here is that no fly depend on the state of the other flies.
I think this should look 'organic'.
...that is, if it works at all, of cource. :sunglasses:

[edit]I feel I ought to apologize for hijacking this thread.
I think you created a nice effect, and your code was short, readable and well commented.
I had planned just to mention that an individual storage container for each 'fly' could be used to have simultaneous fadeing. One thing led to the other, and suddenly I had a compiling miniproject :)[/edit]

I don't mind at all. I don't consider this thread hijacked. If there are other thoughts about how to make it more realistic or interesting in some way, I welcome the input. What you're suggesting, however, is a little beyond me at this time. I'm interested in seeing how your variation comes out, though. Please keep me posted.

Poke the LED's through a sheet of white laminex sloped slightly inwards and over a rectangular trough. put 1/4 inch of car oil in the bottom and use it as a trap.

Could another thread be started and run at the same time then it would randomise differently in each thread. Don't know if arduino can handle threads yet?

AlphaBeta that's exactly what I looking for, a code to act like the impatient fire flies. I didn't describe it very well though.

Unfortunately this project seems to be well over my head though. I keep getting an error compiling and can't clear it. Bummer.

In function 'void randomizeFlies()':
error: 'class TimedAction' has no member named 'setInterval'

http://www.arduino.cc/playground/Code/TimedAction
Download the newest version. :slight_smile:

[I just uploaded it. My bad. :-[]

Thanks AlphaBeta, it's running now.
I'll have to do some studying and try to get a grasp on this sketch and what makes it tick.

Right now it's more of a fire fly disco tech but the blinks are overlapping (just not randomly or nice and slow like in nature). Have to try some number switching and see if it calms down this over caffeinated display of LED goodness.

const byte MAX_FADE_INCREMENT = 5; //lower to slow down
const byte MIN_FADE_INCREMENT = 2; //lower to slow down
const byte TICK_FREQUENCY = 5; //increase to slow down

:slight_smile:

Thank you so much for this post, I'm needing to make some firefly effect for a show and this really helped. the code AlphaBeta contributed works great! I can't wait to play with it more.