Skip to content

Instantly share code, notes, and snippets.

@benwilhelm
Created December 15, 2014 17:00
Show Gist options
  • Save benwilhelm/2d050303d5f17175a4e9 to your computer and use it in GitHub Desktop.
Save benwilhelm/2d050303d5f17175a4e9 to your computer and use it in GitHub Desktop.
Firefly Loop for Arduino
const int numPins = 10 ;
int pins[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } ;
int up[numPins] ;
int dur[numPins] ;
int dn[numPins] ;
int cyc[numPins] ;
long prv[numPins] ;
long currentMillis ;
int maxBright = 100 ;
int cycMin = 8000 ;
int cycMax = 16000 ;
int upMin = 200 ;
int upMax = 400 ;
int durMin = 300 ;
int durMax = 500 ;
int dnMin = 150 ;
int dnMax = 350 ;
void setup() {
Serial.begin(9600) ;
enablePins() ;
testPins() ;
for (int i=0; i<=numPins-1; i++) {
cyc[i] = random(cycMin,cycMax) ;
up[i] = random(upMin,upMax) ;
dur[i] = random(durMin,durMax) ;
dn[i] = random(dnMin,dnMax) ;
prv[i] = 0 ;
}
}
void loop() {
//int potRead = analogRead(A0) ;
for (int i=0; i<=numPins-1; i++) {
setBrightness(i) ;
}
}
void setBrightness(int pinIdx) {
int brightness ;
currentMillis = millis() ;
long elps = currentMillis - prv[pinIdx] ;
int pinId = pins[pinIdx] ;
int pinUp = up[pinIdx] ;
int pinDur = dur[pinIdx] ;
int pinDn = dn[pinIdx] ;
int pinCyc = cyc[pinIdx] ;
// fade up
if (elps < pinUp) {
brightness = map(elps,0,pinUp,0,maxBright) ;
// on duration
} else if (elps < pinUp + pinDur) {
brightness = maxBright ;
// fade down
} else if (elps < pinUp + pinDur + pinDn) {
int dnElps = elps - (pinUp + pinDur) ;
brightness = map(dnElps,0,pinDn,maxBright,0) ;
// dormant
} else if (elps < pinCyc) {
brightness = 0 ;
// reset
} else {
brightness = 0 ;
prv[pinIdx] = currentMillis ;
cyc[pinIdx] = random(cycMin,cycMax) ;
}
// set brightness
analogWrite(pinId,brightness) ;
}
void enablePins() {
for (int pin=2; pin<=13; pin++) {
pinMode(pin,OUTPUT) ;
}
}
void testPins() {
int pin ;
for (pin=2; pin<=13; pin++) {
digitalWrite(pin, HIGH) ;
delay(75) ;
digitalWrite(pin, LOW) ;
}
delay(100) ;
for (pin=2; pin<=13; pin++) {
digitalWrite(pin, HIGH) ;
}
delay(1000) ;
for (pin=2; pin<=13; pin++) {
digitalWrite(pin, LOW) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment