myFirstProject

Hi all,

I got my first arduino over a month ago and already learned a lot. Today I succeeded in getting 8 leds randomly blinking for a certain amount of time after triggering it with a pir sensor.

No rocket science nor brain surgery but I'm a happy camper for sure!

Code below, I'm sure it can be done better in less code but I'm proud of it! Thanks to you all for providing the vast amount of information, examples and inspiration

/*
pir sensor set to retrigger
and shortest delay time

blink runtime is loopSpeed / 1000 * upTime

*/

// init
int ledPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
int ledState[] = {0, 0, 0, 0, 0, 0, 0, 0};
int pinCount = 8;
int loopSpeed = 500;
int upTime = 20;
int randNumber;

int pirPin = 3;
int pirState = LOW;
int val = 0;

// setup
void setup(){
  for(int thisPin = 0; thisPin < pinCount; thisPin++){
    pinMode(ledPins[thisPin], OUTPUT);
    randomSeed(analogRead(0));
  }
  //test all leds with a kit-scan
  for(int thisPin = 0; thisPin < pinCount; thisPin++){
    digitalWrite(ledPins[thisPin], HIGH);
    delay(100);
  }
  for(int thisPin = 0; thisPin < pinCount; thisPin++){
    digitalWrite(ledPins[thisPin], LOW);
    delay(100);
  }
  for(int thisPin = pinCount-1; thisPin >=0; thisPin--){
    digitalWrite(ledPins[thisPin], HIGH);
    delay(100);
  }
  for(int thisPin = pinCount-1; thisPin >=0; thisPin--){
    digitalWrite(ledPins[thisPin], LOW);
    delay(100);
  }
delay(1000);  
}

void loop(){
  val = digitalRead(pirPin);
  if (val == HIGH){
    for (int counter = 0; counter <= upTime; counter++){
      randNumber = random(pinCount);
      if (ledState[randNumber] == 0){
        ledOn();
      }
      else{
        ledOff();
      }
      delay(loopSpeed);
    }
  }
  else {
    for(int thisPin = 0; thisPin < pinCount;  thisPin++){
      digitalWrite(ledPins[thisPin], LOW);
      digitalWrite(ledState[thisPin], 0);
      delay(loopSpeed);
    }
  }
}


void ledOn(){
  digitalWrite(ledPins[randNumber], HIGH);
  ledState[randNumber] = 1;
}


void ledOff(){
  digitalWrite(ledPins[randNumber], LOW);
  ledState[randNumber] = 0;
}

regards, Bert(uino)

pir_led_project_2.ino (1.62 KB)

Well done.
I can read through the code and understand what it is doing without any effort, that's very good.
A few comments extra and placing some code in one or two functions could improve it.

Very nice. I'm in the midst of using Arduinos in an art installation for the first time as well, and it involves getting an RGB LED to blink with random colors whenever a button is pushed. Hasn't worked yet, but it's just a matter of time...

A question: Why did you have to test all the LEDs with a kit-scan?

The kitscan is just for fun, but it also proves my resistors and leds are firmly in the breadboard.