Hello, I am currently working on a stem project making a midi piano out of arduino. I am having a hard time getting the code to work, but I'm not sure if its because of the MIDIUSB library or the code itself. Please help
#include <MIDIUSB.h> // Include the MIDIUSB library
#define NOTE_D 60 // MIDI note number for D4
#define NOTE_E 62 // MIDI note number for E4
#define NOTE_F 63 // MIDI note number for F4
#define NOTE_G 65 // MIDI note number for G4
#define MIDI_CHANNEL 1 // Define MIDI channel
#define MIDIUSB
const int notes[] = {NOTE_D, NOTE_E, NOTE_F, NOTE_G};
int lastNote = -1; // Store the last note played
void setup() {
Serial.begin(9600);
}
void loop() {
// Check for incoming MIDI messages
while (available() > 0) {
midiEventPacket_t event = read(); // Read a MIDI event
handleMIDIEvent(event); // Handle the event if necessary
}
int keyVal = analogRead(A0); // Read from the analog pin
Serial.println(keyVal);
if (keyVal == 1023) {
playNoteIfChanged(notes[0]); // D4
}
else if (keyVal >= 990 && keyVal <= 1010) {
playNoteIfChanged(notes[1]); // E4
}
else if (keyVal >= 505 && keyVal <= 515) {
playNoteIfChanged(notes[2]); // F4
}
else if (keyVal >= 5 && keyVal <= 10) {
playNoteIfChanged(notes[3]); // G4
}
else {
if (lastNote != -1) {
sendNoteOff(lastNote); // Stop the last note
lastNote = -1; // Reset last note
}
}
delay(100); // Debounce delay
}
void handleMIDIEvent(midiEventPacket_t event) {
if (event.header != 0) { // Check if there's a valid MIDI message
Serial.print("MIDI Message: ");
Serial.print(event.byte1, HEX); // Print the first byte of the MIDI message
Serial.print(" ");
Serial.print(event.byte2, HEX); // Print the second byte (note)
Serial.print(" ");
Serial.println(event.byte3, HEX); // Print the third byte (velocity)
}
}
void playNoteIfChanged(byte note) {
if (note != lastNote) {
if (lastNote != -1) {
sendNoteOff(lastNote); // Stop the last note before playing a new one
}
sendNoteOn(note); // Start the new note
lastNote = note; // Update last note
}
}
void sendNoteOn(byte note) {
midiEventPacket_t event = {0x09 | (MIDI_CHANNEL - 1), note, 127}; // Note On message
sendMIDI(event); // Send the MIDI message
}
void sendNoteOff(byte note) {
midiEventPacket_t event = {0x08 | (MIDI_CHANNEL - 1), note, 0}; // Note Off message
sendMIDI(event); // Send the MIDI message
}
void sendMIDI(midiEventPacket_t event) {
MIDIUSB.send(event); // Correct way to send the MIDI event
MIDIUSB.flush(); // Wait for all messages to be sent
}
uint32_t available() {
return MIDIUSB.available(); // Return the number of available MIDI messages
}
midiEventPacket_t read() {
return MIDIUSB.read(); // Read a MIDI event from USB
}