Digital Lecture 10

pressCallback and releaseCallback are variable functions. Each one holds a function as a variable. This allows for the flexibility demonstrated in our program today. When we change the onPress and onRelease functions, they are updated in the variable.

#include "Button.h"

Button buttonOne(36, 0);
Button buttonTwo(35, 1);
Button buttonThree(34, 2);
Button buttonFour(33, 3);

int ledPins[4] = {29, 30, 31, 32};
int midiNotes[4] = {60, 62, 64, 65};
int total = 4;

void setup() {
  Serial.begin(9600);

  for(int i = 0; i < total; i++){
    pinMode(ledPins[i], OUTPUT);
  }
  
  buttonOne.pressHandler(onPress);
  buttonOne.releaseHandler(onRelease);
  buttonTwo.pressHandler(onPress);
  buttonTwo.releaseHandler(onRelease);
  buttonThree.pressHandler(onPress);
  buttonThree.releaseHandler(onRelease);
  buttonFour.pressHandler(onPress);
  buttonFour.releaseHandler(onRelease);
}

void loop() {
  buttonOne.process();
  buttonTwo.process();
  buttonThree.process();
  buttonFour.process();
}

void onPress(int buttonNumber) {
  Serial.print(buttonNumber);
  Serial.println(" pressed");
  digitalWrite(ledPins[buttonNumber], HIGH);
  usbMIDI.sendNoteOn(midiNotes[buttonNumber], 127, 1);
}

void onRelease(int buttonNumber) {
  Serial.print(buttonNumber);
  Serial.println(" released");
  digitalWrite(ledPins[buttonNumber], LOW);
  usbMIDI.sendNoteOff(midiNotes[buttonNumber], 0, 1);
}

Leave a comment

Design a site like this with WordPress.com
Get started