Skip to content

Instantly share code, notes, and snippets.

@oshoham
Forked from boysonhudson/laser_harp.ino
Last active June 15, 2022 13:14
Show Gist options
  • Save oshoham/f352a4627e7b0a9f6c5941fad8a1a590 to your computer and use it in GitHub Desktop.
Save oshoham/f352a4627e7b0a9f6c5941fad8a1a590 to your computer and use it in GitHub Desktop.
Laser Harp Arduino Code
/*
* Laser Harp MIDI Controller
*
* Authors: Wei-Luen (Alan) Peng and Oren Shoham
*/
// hex to MIDI note reference: https://www.wavosaur.com/download/midi-note-hex.php
// scale: B5, A5, G5, F5, E5, D5, C5
const int notes[7] = {0x5F, 0x5D, 0x5B, 0x59, 0x58, 0x56, 0x54};
const int startingInputPin = 3;
//
int photoDiodes[7] = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
bool noteState[7] = {false, false, false, false, false, false, false};
void setup() {
// baud rate is 57600 because the serial to MIDI converter software recommends it
Serial.begin(57600);
}
void loop() {
for (int i = 0; i < 7; i++) {
int pin = i + startingInputPin;
photoDiodes[i] = digitalRead(pin);
}
// uncomment the following line to help debug the photodiode input values
// printPhotoDiodeValues();
writeMIDINotes();
}
// print photodiode values for debugging
void printPhotoDiodeValues() {
for (int i = 0; i < 7; i++) {
Serial.print("value ");
Serial.print(i);
Serial.print(": ");
Serial.print(photoDiodes[i]);
if (i != 6) {
Serial.print(", ");
} else {
Serial.println("");
}
}
}
// write MIDI notes for each photodiode that is off
// if a photodiode is off, the laser is being blocked by something
void writeMIDINotes() {
for (int i = 0; i < 7; i++) {
checkPhotoDiodeState(i);
}
}
// for each photodiode/note:
// if the beam is interrupted and the note was off, turn it on
// if the beam is not interrupted and the note was on, turn it off
void checkPhotoDiodeState(int index) {
int value = photoDiodes[index];
int note = notes[index];
bool noteIsOn = noteState[index];
if (value == LOW && noteIsOn == false) {
noteState[index] = true;
playNote(note);
} else if(value == HIGH && noteIsOn == true) {
noteState[index] = false;
silenceNote(note);
}
}
void playNote(int note) {
noteOn(0x90, note, 0x45);
}
void silenceNote(int note) {
noteOn(0x90, note, 0x00);
}
// reference: https://www.arduino.cc/en/Tutorial/Midi
// plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that
// data values are less than 127:
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment