18 septembre 2011

Experiments with the Arduino - Controlling 5 LEDs

The circuit


The code

void ledOn(int nr, int high = HIGH, int low = LOW) {

  for(int j = 1; j <= 5; j++) {
    if (nr == j) {
      digitalWrite(j, high);
    } else {
      digitalWrite(j, low);
    }
  }
}

void ledsOn(
  int wait,
  int l1 = LOW, 
  int l2 = LOW, 
  int l3 = LOW, 
  int l4 = LOW, 
  int l5 = LOW) {

  digitalWrite(1, l1);
  digitalWrite(2, l2);
  digitalWrite(3, l3);
  digitalWrite(4, l4);
  digitalWrite(5, l5);
  delay(wait);
}

void backAndForth(int nr, int wait, int high = HIGH, int low = LOW) {

  for(int t = 1; t <= nr; t++) {
    for(int i = 2; i <= 5; i++) {
      ledOn(i, high, low);
      delay(wait);          
    }
    for(int i = 4; i >= 1; i--) {
      ledOn(i, high, low);
      delay(wait);          
    }
  }
}

void fallingBrick(int wait, int high = HIGH, int low = LOW) {

  for(int i = 1; i <= 5; i++) {
    for(int j= 1; j <= 6 - i; j ++) {
      ledOn(j, high, low);
      for(int k = 7 - i; k <= 5; k++) {
        digitalWrite(k, high);
      }
      delay(wait);
    }
  }  
}

void boing(int nr, int wait) {
  
  for(int i = 1; i < nr; i++) {
    ledsOn(wait, 0, 0, 1, 0, 0);
    ledsOn(wait, 0, 1, 1, 1, 0);
    ledsOn(wait * 2, 1, 1, 1, 1, 1);
    ledsOn(wait, 0, 1, 1, 1, 0);
    ledsOn(wait, 0, 0, 1, 0, 0);
    ledsOn(wait * 2, 0, 0, 0, 0, 0);
  }
}

void wave(int nr, int wait) {
  
  for(int i = 1; i < nr; i++) {
    ledsOn(wait, 1, 0, 0, 0, 0);
    ledsOn(wait, 1, 1, 0, 0, 0);
    ledsOn(wait, 1, 1, 1, 0, 0);
    ledsOn(wait, 1, 1, 1, 1, 0);
    ledsOn(wait * 2, 1, 1, 1, 1, 1);
    ledsOn(wait, 1, 1, 1, 1, 0);
    ledsOn(wait, 1, 1, 1, 0, 0);
    ledsOn(wait, 1, 1, 0, 0, 0);
    ledsOn(wait * 2, 1, 0, 0, 0, 0);
  }
}

void setup() {                
  for(int i = 1; i <= 5; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  
  int baf_wait = 50;
  int fb_wait = 100;

  wave(5, 50);
  delay(1000);
  backAndForth(5, 50);
  delay(1000);
  fallingBrick(100);
  delay(1000);
  backAndForth(5, 50, LOW, HIGH);
  delay(1000);
  fallingBrick(100, LOW, HIGH);
  delay(1000);
  boing(5, 50);
  delay(1000);
}

The result

Aucun commentaire:

Enregistrer un commentaire