Skip to content

Instantly share code, notes, and snippets.

@tomatosoupcan
Created November 1, 2024 23:12
Show Gist options
  • Save tomatosoupcan/0e28ca85f7d6b56d1ec42a2d7e141417 to your computer and use it in GitHub Desktop.
Save tomatosoupcan/0e28ca85f7d6b56d1ec42a2d7e141417 to your computer and use it in GitHub Desktop.
An Arduino Sketch for creating a Keyboard/MidiKeyboard controlled by a single soldered keyboard switch
#include <Keyboard.h>
#include <MIDIUSB.h>
int readValue = 0;
int lastValue = 1;
char mode = 'K';
byte midiCh = 2;
byte note = 36;
byte cc = 1;
void setup() {
pinMode(PIN_A2, OUTPUT);
pinMode(PIN_A4, INPUT_PULLUP);
digitalWrite(PIN_A2, LOW);
}
void loop() {
delay(500);
readValue = digitalRead(PIN_A4);
if (lastValue != readValue) {
if (readValue) {
if (mode == 'K') {
sendKey(KEY_F21);
}
else {
sendNote(note);
}
}
else {
if (mode == 'K') {
sendKey(KEY_F20);
}
else {
sendNote(note+1);
}
}
}
lastValue = readValue;
}
void sendKey(char key) {
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(key);
delay(100);
Keyboard.releaseAll();
}
void sendNote(int note) {
noteOn(midiCh, note, 127);
MidiUSB.flush();
delay(100);
noteOff(midiCh, note, 127);
MidiUSB.flush();
}
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);
}
void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment