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)];
}