Digital Electrics Lab 8

Below is my code:

int buttonPin[4] = { 33, 34, 35, 36 };
int totalButtonPins = 4;

int ledPin[4] = { 8, 9, 10, 11 };
int totalLeds = 4;

bool lastButton1State[4] = { LOW, LOW, LOW, LOW };
bool button1State[4] = { LOW, LOW, LOW, LOW };

bool switchedOn[4] = { false, false, false, false };

unsigned long lastStepTime = 0;
int currentStep = 0;
int totalSteps = 4;
int tempo = 200;

void setup() {
  for (int i = 0; i < totalLeds; i++) {
    pinMode(ledPin[i], OUTPUT);
  }
  for (int i = 0; i < totalButtonPins; i++) {
    pinMode(buttonPin[i], INPUT);
  }
}

void loop()
{
  checkButtons();
  updateLeds();
  sequenceForwards();
}

void checkButtons() {
  for (int i = 0; i < buttonPin[i]; i++) {
    lastButton1State[i] = button1State[i];
    button1State[i] = digitalRead(buttonPin[i]);
    if (lastButton1State[i] == LOW && button1State[i] == HIGH) {
      switchedOn[i] = !switchedOn[i]; // this means: if switchedOn is true then set it to false, if switchedOn is false then set it to true
      delay(5);
    } else if (lastButton1State[i] == HIGH && button1State[i] == LOW) {
      delay(5);
    }
  }
}

void updateLeds() {
  for (int i = 0; i < ledPin[i]; i++) {
    if (switchedOn[i] == true) {
      digitalWrite(ledPin[i], HIGH);
    } else {
      digitalWrite(ledPin[i], LOW);
    }
  }
  digitalWrite(ledPin[currentStep], HIGH);
}

void sequenceForwards() {
  if (millis() >= lastStepTime + tempo) {
    lastStepTime = millis();
    usbMIDI.sendNoteOff(60, 0, 1);
    countUp();
    if (switchedOn[currentStep] == HIGH) {
      usbMIDI.sendNoteOn(60, 127, 1);
    }
  }
}

void countUp() {
  currentStep++;
  if (currentStep == totalSteps) {
    currentStep = 0;
  }
}

Leave a comment

Design a site like this with WordPress.com
Get started