Hi all,
I'm attempting to simulate some fireflies with 16 LEDs and an Arduino MEGA2560. I've got them running smoothly in a basic random blinking sketch, but I'm now trying to get them to blink an average of 7 times per LED, then all go dark for 5-8 seconds, then start back up again. When I run the code, the LEDs perform as expected for the first cycle, but after the first synchronized dark period, they behave strangely. The LEDs will all flash on and off very rapidly all together a couple of times, then go back to the expected slower random blinking until blinkCount is reached. Below is my code, bit of a doozy but any help would be greatly appreciated!
int blinkCount = 0; //track number of blinks for synchronized dark period
int LED[] = {53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, 31, 29, 27, 25, 23}; //pin values for each LED
unsigned long prevBlink[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //track time of most recent state change
int blinkDelay[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //initial delay values
byte state[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW}; //set initial pin states to off (low)
bool checkStates() { //check if states of all LEDs are LOW or not
for (int i = 0; i < 16; i++){
if (state[i] != LOW) {
return false;
}
}
return true;
}
void setup() {
Serial.begin(9600); //DEBUGGING
for (int i = 0; i < 16; i++) {
pinMode(LED[i], OUTPUT);
}
}
void blinkLEDs() { //function to handle blinking of LEDs
while (blinkCount <= 224) {
unsigned long timeNow = millis(); //get current time
for (int i = 0; i < 16; i++) {
//if time passed since last toggle > blink delay, toggle given LED
if (timeNow - prevBlink[i] > blinkDelay[i]) {
prevBlink[i] += blinkDelay[i]; //set new previous toggle time
if (state[i] == LOW) { //change LED state
state[i] = HIGH;
}
else {
state[i] = LOW;
}
digitalWrite(LED[i], state[i]); //toggle LED
blinkDelay[i] = random(500, 1000); //set new random blink delay between half a second and 1 second
blinkCount++;
Serial.println(blinkCount); //DEBUGGING
}
}
}
}
void loop() {
unsigned long timeNow = millis(); //get current time
if (blinkCount >= 224) { //if number of toggles > 224 (average of 7 blinks per firefly)
for (int i = 0; i < 16; i++) {
//turn off each LED after blink delay completes
if (timeNow - prevBlink[i] > blinkDelay[i] && state[i] == HIGH) {
state[i] = LOW;
digitalWrite(LED[i], LOW);
prevBlink[i] += blinkDelay[i];
blinkDelay[i] = random(500, 1000);
if (checkStates() == true) {
delay(random(5000, 8000)); //wait 5-8 seconds before resuming flashing
blinkCount = 0;
}
}
}
}
else {
blinkLEDs();
}
}