Digital Electrics Lab 9

Below is my code:

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

int ledPin[4] = { 22, 21, 20, 19 };
int totalLeds = 4;

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

boolean switchedOn[3][4] = {
  { LOW, LOW, LOW, LOW },
  { LOW, LOW, LOW, LOW },
  { LOW, LOW, LOW, LOW }
};

int channelDisplayed = 0;
int channelLedPin[3] = { 8, 9, 10 };
int totalChannelLeds = 3;
int totalChannelSteps = 3;

int channelButton = 32;
bool lastChannelButtonState = LOW;
bool channelButtonState = LOW;

int midiNotes[3] = { 60, 64, 67 };

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);
  }
  for (int i = 0; i < totalChannelLeds; i++) {
    pinMode(channelLedPin[i], OUTPUT);
  }
  pinMode(channelDisplayed, INPUT);
  pinMode(channelButton, INPUT);
}


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

void checkButtons() {
  for (int i = 0; i < 4; i++) {
    lastButton1State[i] = button1State[i];
    button1State[i] = digitalRead(buttonPin[i]);
    if (lastButton1State[i] == LOW && button1State[i] == HIGH) {
      switchedOn[channelDisplayed][i] = !switchedOn[channelDisplayed][i];
      delay(5);
    }
    else if (lastButton1State[i] == HIGH && button1State[i] == LOW) {
      delay(5);
    }
  }
}

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

void sequenceForwards() {
  if (millis() >= lastStepTime + tempo) {
    lastStepTime = millis();
    for (int i = 0; i < 3; i++) {
      usbMIDI.sendNoteOff(midiNotes[i], 0, 1);
    }
    countUp();

    for (int i = 0; i < 3; i++) {
      if (switchedOn[i][currentStep] == HIGH) {
        usbMIDI.sendNoteOn(midiNotes[i], 127, 1);
      }
    }
  }
}
void countUp() {
  currentStep++;
  if (currentStep == totalSteps) {
    currentStep = 0;
  }
}

void channelStep() {
  channelButtonState = digitalRead(channelButton);
  if (channelButtonState == HIGH && lastChannelButtonState == LOW) {
    channelDisplayed++;
    if (channelDisplayed == totalChannelSteps) {
      channelDisplayed = 0;
    }
    delay(5);
    Serial.println(channelDisplayed);
  }
  else if (channelButtonState == LOW && lastChannelButtonState == HIGH) {
    delay(5);
  }
  lastChannelButtonState = channelButtonState;
}

void channelLed() {
  for (int i = 0; i < 3; i++) {
    if (channelDisplayed == i) {
      digitalWrite(channelLedPin[i], HIGH);
    }
    else {
      digitalWrite(channelLedPin[i], LOW);
    }
  }
}

Leave a comment

Design a site like this with WordPress.com
Get started