Digital Lab 8

Aidan Singh


int ledPin [4] = {29,30,31,32};
int buttonPin [4] = {33,34,35,36};
int switchPin = 38;
bool lastButtonState [4] = {LOW,LOW,LOW,LOW};
bool buttonState [4] = {LOW,LOW,LOW,LOW};
bool switchedOn[4] = {false,false,false,false};

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

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

void loop(){
  if(digitalRead(switchPin) == HIGH){ //checks forwards/backwards button
    stepForwards();
  }else{
  stepBackwards();}
  tempo =analogRead(A18);
  checkButtons();
  updateLeds();
}

void stepForwards(){
  if(millis() >= lastStepTime + tempo) {
    lastStepTime = millis();
    usbMIDI.sendNoteOff(39, 0, 1);//SENDS MIDI NOTE OFF
    currentStep++;
    if(currentStep == totalSteps){
      currentStep = 0;
    }
    if(switchedOn[currentStep] == true) //SENDS MIDI NOTE ON
    usbMIDI.sendNoteOn(39, 90, 1);
  }
 }

 void stepBackwards(){
  if(millis() >= lastStepTime + tempo) {
    lastStepTime = millis();
    usbMIDI.sendNoteOff(39, 0, 1);//SENDS MIDI NOTE OFF
    currentStep--;
    if(currentStep < 0){
      currentStep = 3;
    }
    if(switchedOn[currentStep] == true) //SENDS MIDI NOTE ON
    usbMIDI.sendNoteOn(39, 90, 1);
  }
}



void checkButtons() {
  for(int i=0;i<4;i++){
  lastButtonState[i] = buttonState[i];
  buttonState[i] = digitalRead(buttonPin[i]);
  if(lastButtonState[i] == LOW && buttonState[i] == HIGH) {
    flipButtonState(i);
    delay(5);
  } else if(lastButtonState[i] == HIGH && buttonState[i] == LOW) {
    delay(5);
  }
  }
}


void flipButtonState(int i) {
    if(switchedOn[i] == true) {
      switchedOn[i] = false;
    } else if(switchedOn[i] == false) {
      switchedOn[i] = true;
    }  
}

void updateLeds() {
  for(int i=0;i<4;i++){
  if(switchedOn[i] == true) {//lights LED if button was pressed
    digitalWrite(ledPin[i], HIGH);
  } else if(currentStep == i){//lights LED of current step
    digitalWrite(ledPin[i], HIGH);
  }
    else {digitalWrite(ledPin[i], LOW);
  }
  }
}

Leave a comment

Design a site like this with WordPress.com
Get started