16 Buttons with 2x 74HC4051, print only status change

Control Surface comes with a Button class that does roughly the same as the Bounce library, and it supports multiplexers out of the box:

#include <Control_Surface.h>

CD74HC4051 mux {
  3,
  {0, 1, 2},
};

// Convert the array of pins of the multiplexer to an 
// array of debounced button objects
Array<Button, 8> buttons = copyAs<Button>(mux.pins());

void setup() {
  Serial.begin(115200);
  mux.begin();
  for (Button &button : buttons)
    button.begin();
}

void loop() {
  uint8_t i = 0;
  for (Button &button : buttons) {
    switch (button.update()) {
      case Button::Pressed: break;
      case Button::Released: break;
      case Button::Falling: Serial << "Button " << i << " was pressed" << endl; break;
      case Button::Rising: Serial << "Button " << i << " was released" << endl; break;
    }
    ++i;
  }
}

However, none of this is necessary if you just want some buttons that send MIDI messages when pressed/released:

#include <Control_Surface.h>

USBMIDI_Interface midi;

CD74HC4051 mux {
  3,
  {0, 1, 2},
};

NoteButton midibuttons[] {
  {mux.pin(0), 0}, // pin, MIDI address (note number, in this example)
  {mux.pin(1), 1},
  {mux.pin(2), 2},
  {mux.pin(3), 3},
  {mux.pin(4), 4},
  {mux.pin(5), 5},
  {mux.pin(6), 6},
  {mux.pin(7), 7},
};

void setup() {
  Control_Surface.begin();
}

void loop() {
  Control_Surface.loop();
}
1 Like