I have a MIDIUSB sketch I am using with mini arcade buttons that have LEDs included in them.
I am looping through an array of the buttons and the LEDs but the LED just stays lit or does not light.
[]-Ground |-5V
[]-Pin 2 |-Pin 6
My goal is if i press button 1 --> led 1 will remain lit until i press another button. I am using the same variable "i" to get the index of the array.
#include "MIDIUSB.h"
#include "PitchToNote.h"
#define NUM_BUTTONS 4
const uint16_t button1 = 2;
const uint16_t button2 = 3;
const uint16_t button3 = 4;
const uint16_t button4 = 5;
const uint16_t led1 = 6;
const uint16_t led2 = 7;
const uint16_t led3 = 8;
const uint16_t led4 = 9;
const uint16_t buttons[NUM_BUTTONS] = {button1, button2, button3, button4};
const uint16_t LEDS[NUM_BUTTONS] = {led1, led2, led3, led4};
const byte notePitches[NUM_BUTTONS] = {pitchC2, pitchD2b, pitchD2, pitchE2b};
uint16_t notesTime[NUM_BUTTONS];
uint16_t pressedButtons = 0x00;
uint16_t previousButtons = 0x00;
uint16_t pressedLEDS = LOW;
uint16_t previousLEDS = HIGH;
uint16_t intensity;
void setup() {
for (int i = 0; i < NUM_BUTTONS; i++)
pinMode(buttons[i], INPUT_PULLUP);
for (int i = 0; i < NUM_BUTTONS; i++)
pinMode(LEDS[i], OUTPUT);
}
void loop() {
readButtons();
readLEDS();
playNotes();
playLEDS();
}
void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}
void readButtons()
{
for (int i = 0; i < NUM_BUTTONS; i++)
{
if (digitalRead(buttons[i]) == LOW)
{
bitWrite(pressedButtons, i, 1);
delay(2);
}
else
bitWrite(pressedButtons, i, 0);
}
}
void playNotes()
{
for (int i = 0; i < NUM_BUTTONS; i++)
{
if (bitRead(pressedButtons, i) != bitRead(previousButtons, i))
{
if (bitRead(pressedButtons, i))
{
bitWrite(previousButtons, i , 1);
noteOn(0, notePitches[i], 100);
MidiUSB.flush();
}
else
{
bitWrite(previousButtons, i , 0);
noteOff(0, notePitches[i], 0);
MidiUSB.flush();
}
}
}
}
void readLEDS()
{
for (int i = 0; i < NUM_BUTTONS; i++)
{
if (bitRead(pressedButtons, i) != bitRead(previousButtons, i))
{
bitWrite(pressedLEDS, i, LOW);
delay(2);
}
else
bitWrite(pressedLEDS, i, HIGH);
}
}
void playLEDS()
{
for (int i = 0; i < NUM_BUTTONS; i++)
{
if (bitRead(pressedButtons, i) != bitRead(previousButtons, i))
{
if (bitRead(pressedLEDS, i))
{
bitWrite(previousLEDS, i, LOW);
}
else
{
bitWrite(previousLEDS, i, HIGH);
}
}
}
}
void noteOn(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOn = {0x09, 0x90 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOn);
}
void noteOff(byte channel, byte pitch, byte velocity) {
midiEventPacket_t noteOff = {0x08, 0x80 | channel, pitch, velocity};
MidiUSB.sendMIDI(noteOff);
}
sketch_may07a.ino (2.68 KB)