A synthesizer that is controlled by a USB MIDI Keyboard. Also displays corresponding frequencies via a simple spectrum analyzer on a LCD. Uses a watchdog timer to reset Mbed in case it freezes.
Dependencies: 4DGL-uLCD-SE USBHostMIDI mbed
Fork of USBHostMIDI_example by
Diff: MIDISpeaker.h
- Revision:
- 2:5366ce17fe55
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/MIDISpeaker.h Wed Dec 13 03:31:09 2017 +0000 @@ -0,0 +1,44 @@ +#include "mbed.h" +#include "uLCD_4DGL.h" + +#define BAUD_9600 312 +// new class to play a note on Speaker based on PwmOut class +uLCD_4DGL uLCD(p9,p10,p11); +int x1; +int y1; +class MIDISpeaker +{ +public: + MIDISpeaker(PinName pin) : _pin(pin) { +// _pin(pin) means pass pin to the Speaker Constructor + } +// class method to play a note based on PwmOut class + void PlayNote(unsigned char note, unsigned char velocity) {//volatile int duration) { + int notef = int(note); //convert note to int + int velocityf = int(velocity); //convert velocity to int + double noteg = double(notef); //convert note to double + double velocityg = double(velocityf); //convert velocity to double + double f_n = double((noteg - 49)/12); //use piano frequency formula to find corresponding frequency + double freq = (pow(2, f_n)) * 440; + _pin.period(1.0/freq); //use frequency to set period of pwmout pin + velocityg = ((velocityg/127.0) * 0.5); //calculate volume of note and set to pwmout pin + _pin = velocityg; + x1 = ((freq/4000)*115) + 5; //calcuate starting position for frequency spectrum [0,4000 Hz] + y1 = 110 - ((_pin/0.5)*105); // calculate magnitude of spectrum based on velocity + uLCD.locate(0,13); + uLCD.printf("\nkey: %d, freq: %4.0f, volume: %.2f\n", note, freq, velocityg); + uLCD.textbackground_color(BLUE); + uLCD.filled_rectangle(x1, y1, x1+2, 109, BLACK); + } + void StopNote() { + _pin = 0.0; + //uLCD.filled_rectangle(x1, y1, x1+2, 109, BLUE); //code to clear rectangle from lcd + } + +private: +// sets up specified pin for PWM using PwmOut class + PwmOut _pin; +}; + +// Speaker test program - earlier euro police style siren now using new class method +// \ No newline at end of file