mbed working as a midi device through usb D-, D+

Dependencies:   USBDevice beep mbed

main.cpp

Committer:
ghostaudio
Date:
2013-11-19
Revision:
0:f24bc002bd2e

File content as of revision 0:f24bc002bd2e:

// Edited from the Hello World example for the USBMIDI library
// to play notes from the PwmOut using beep.....

#include "mbed.h"
#include "USBMIDI.h"
#include "beep.h"

//USBMIDI object
USBMIDI midi;

Beep buzzer(p22); // piezo one of two( this only needs one,
Beep buzzer2(p21); // but piezo two made it more fun).....
AnalogIn pot (p19); // and a potentiometer.....

int freq = 0;

// an array of frequencies from C2-C4 for freq.....
int freqs[] = {261,277,293,311,329,349,369,391,415,440,466,493,523,
                554,587,622,659,698,739,783,830,880,932,987,1046};

//defining your midi notes as points in the array.....
void show_message(MIDIMessage msg) {
    if (msg.type() == MIDIMessage::NoteOnType) {
        if (msg.velocity()!=0) {
            freq = freqs[(msg.key()-48)];
        }
        else {
            freq = 0;
        }
    }
}

int main() {
    
    // call back for midi messages received
    midi.attach(show_message);
    
    while (1) {
    
    float time = (pot/2); // assign the pot to the time...
    if (freq > 0){
        buzzer.beep(freq,0.1); // between this beep...
        wait (time);
        buzzer2.beep((freq*2),0.1); // and this beep (1 octave up).
        wait (time);
        }
    
    wait (0.0001); // wait a millesecond and carry on...
    }
}