|
| 1 | +/* |
| 2 | + * MIDIUSB_buzzer.ino |
| 3 | + * |
| 4 | + * Author: Paulo Costa |
| 5 | + */ |
| 6 | + |
| 7 | +#include <MIDIUSB.h> |
| 8 | +#include "pitchToFrequency.h" |
| 9 | + |
| 10 | +#define BUZZ_PIN 9 |
| 11 | + |
| 12 | +const char* pitch_name(byte pitch) { |
| 13 | + static const char* names[] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; |
| 14 | + return names[pitch % 12]; |
| 15 | +} |
| 16 | + |
| 17 | +int pitch_octave(byte pitch) { |
| 18 | + return (pitch / 12) - 1; |
| 19 | +} |
| 20 | + |
| 21 | +void noteOn(byte channel, byte pitch, byte velocity) { |
| 22 | + tone(BUZZ_PIN, pitchFrequency[pitch]); |
| 23 | + |
| 24 | + Serial.print("Note On: "); |
| 25 | + Serial.print(pitch_name(pitch)); |
| 26 | + Serial.print(pitch_octave(pitch)); |
| 27 | + Serial.print(", channel="); |
| 28 | + Serial.print(channel); |
| 29 | + Serial.print(", velocity="); |
| 30 | + Serial.println(velocity); |
| 31 | +} |
| 32 | + |
| 33 | +void noteOff(byte channel, byte pitch, byte velocity) { |
| 34 | + noTone(BUZZ_PIN); |
| 35 | + |
| 36 | + Serial.print("Note Off: "); |
| 37 | + Serial.print(pitch_name(pitch)); |
| 38 | + Serial.print(pitch_octave(pitch)); |
| 39 | + Serial.print(", channel="); |
| 40 | + Serial.print(channel); |
| 41 | + Serial.print(", velocity="); |
| 42 | + Serial.println(velocity); |
| 43 | +} |
| 44 | + |
| 45 | +void controlChange(byte channel, byte control, byte value) { |
| 46 | + Serial.print("Control change: control="); |
| 47 | + Serial.print(control); |
| 48 | + Serial.print(", value="); |
| 49 | + Serial.print(value); |
| 50 | + Serial.print(", channel="); |
| 51 | + Serial.println(channel); |
| 52 | +} |
| 53 | + |
| 54 | +void setup() { |
| 55 | + Serial.begin(115200); |
| 56 | +} |
| 57 | + |
| 58 | +void loop() { |
| 59 | + midiEventPacket_t rx = MidiUSB.read(); |
| 60 | + switch (rx.header) { |
| 61 | + case 0: |
| 62 | + break; //No pending events |
| 63 | + |
| 64 | + case 0x9: |
| 65 | + noteOn( |
| 66 | + rx.byte1 & 0xF, //channel |
| 67 | + rx.byte2, //pitch |
| 68 | + rx.byte3 //velocity |
| 69 | + ); |
| 70 | + break; |
| 71 | + |
| 72 | + case 0x8: |
| 73 | + noteOff( |
| 74 | + rx.byte1 & 0xF, //channel |
| 75 | + rx.byte2, //pitch |
| 76 | + rx.byte3 //velocity |
| 77 | + ); |
| 78 | + break; |
| 79 | + |
| 80 | + case 0xB: |
| 81 | + controlChange( |
| 82 | + rx.byte1 & 0xF, //channel |
| 83 | + rx.byte2, //control |
| 84 | + rx.byte3 //value |
| 85 | + ); |
| 86 | + break; |
| 87 | + |
| 88 | + default: |
| 89 | + Serial.print("Unhandled MIDI message: "); |
| 90 | + Serial.print(rx.header, HEX); |
| 91 | + Serial.print("-"); |
| 92 | + Serial.print(rx.byte1, HEX); |
| 93 | + Serial.print("-"); |
| 94 | + Serial.print(rx.byte2, HEX); |
| 95 | + Serial.print("-"); |
| 96 | + Serial.println(rx.byte3, HEX); |
| 97 | + } |
| 98 | +} |
| 99 | + |
0 commit comments