Randomly and independent blinking LEDs with adjustable half-life

Posted by kantch

kantch's picture

I wrote an exponentially distributed random blinker capable of independently controlling several LEDs in parallel. Basically, the user sets up the interval of time during which the LED has a probability of 1/2 of blinking (half-life).

 

//An exponentially distributed blinker
 
byte outpins[] = {13, 12, 11}; //output pins
#define TAU 1000. //half-life in ms: interval of time 
#define CYCLE 10 //sampling rate in ms
#define ON 1 //number of cycles the output stays on
 
#define PRECISION 32767
#define THRESHOLD PRECISION*pow(2, -CYCLE/TAU)
#define SIZE (sizeof(outpins)/sizeof(byte))
 
byte ttl[SIZE];
 
void setup(){
  for(int i=0; i<SIZE; i++){
    pinMode(outpins[i],OUTPUT);
  }
  randomSeed(analogRead(0)+analogRead(1)+analogRead(2));
}
 
void loop(){
  for(int i=0; i<SIZE; i++){
    if(random(PRECISION) > THRESHOLD){
      ttl[i] = ON;
    }else{
      ttl[i] = max(0,ttl[i]-1);
    }
  }
  
  for(int i=0; i<SIZE; i++){
    if(ttl[i]>0){
      digitalWrite(outpins[i],HIGH);
    }else{
      digitalWrite(outpins[i],LOW);
    }
  }
  delay(CYCLE);
}
 
blinking led on pin 12
5
Your rating: None Average: 5 (1 vote)