Digital Electronics Lecture Assignment #4

Simplifying Code Using an Array and Loops

Video:

Code:

// make variable for each of the components on the breadboard
int ledArray[4] = {7, 8, 9, 10};

int buttonPin = 33;
int buttonPin2 = 34;
int potValue = 0;
int slideSwitch = 32;
int totalLeds = 4;

void setup() {

  for (int i = 0; i < totalLeds; i++) {
    pinMode(ledArray[i], OUTPUT);
  }

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(slideSwitch, INPUT);
}

void loop() {
  potValue = analogRead(A12);

  if (digitalRead(buttonPin) == HIGH) {
    turnOnAllLeds();
    delay(potValue);
    turnOffAllLeds();
    delay(potValue);
  }


  if (digitalRead(buttonPin2) == HIGH and digitalRead(slideSwitch) == LOW) {
    blinkForward();
  }

  if (digitalRead(buttonPin2) == HIGH and digitalRead(slideSwitch) == HIGH) {
    blinkBackwards();
  }


}

void turnOnAllLeds() {
  for (int i = 0; i < totalLeds; i++) {
    digitalWrite(ledArray[i], HIGH);
  }
}

void turnOffAllLeds() {
  for (int i = 0; i < totalLeds; i++) {
    digitalWrite(ledArray[i], LOW);
  }
}

void blinkForward() {
  for (int i = 0; i < totalLeds; i++) {
    digitalWrite(ledArray[i], HIGH);
    delay(potValue);
    digitalWrite(ledArray[i], LOW);
    delay(potValue);
  }
}

void blinkBackwards() {
  for (int i = 3; i >= 0; i--) {
    digitalWrite(ledArray[i], HIGH);
    delay(potValue);
    digitalWrite(ledArray[i], LOW);
    delay(potValue);

  }
}


Leave a comment

Design a site like this with WordPress.com
Get started