A MIDI piano synthesizer that implements the Karplus Strong physical modeling algorithm.

Dependencies:   mbed USBDevice PinDetect

main.cpp

Committer:
asuszek
Date:
2016-04-25
Revision:
22:b800e1766647
Parent:
18:26d93c5b9bb6

File content as of revision 22:b800e1766647:

/* Karplus Strong MIDI synthesizer.
 *
 * @author Austin Suszek
 * @author Nick Delfino
 */

#include "Audio/AudioEngine.h"
#include "Constants.h"
#include "mbed.h"
#include "PinDetect.h"
#include "USBMIDI.h"
#include "LEDController.h"

Serial pc(USBTX, USBRX);

USBMIDI midi;
AudioEngine audioEngine;
LEDController ledController;

// Initialize the LEDs on the controller.
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
// Reuse the binary clock from the homework.
extern "C" int my_leds(int value);

// Buttons for the toggling of synths.
PinDetect nextSynth(p27);
PinDetect prevSynth(p28);

void midiMessageReceived(MIDIMessage message);

void nextSynthPressed();
void prevSynthPressed();

int main() { 
    // Attach the function to handle all incoming MIDI events.
    midi.attach(midiMessageReceived); 
    
    // Attach the synth toggling buttons.
    nextSynth.attach_asserted(&nextSynthPressed);
    prevSynth.attach_asserted(&prevSynthPressed);
    nextSynth.setSampleFrequency();
    prevSynth.setSampleFrequency();
    
    // Start the index counter at number 1.
    my_leds(1);
        
    while (1) {}
}

/*
 * The handler for all incoming MIDI messages.
 */
void midiMessageReceived(MIDIMessage message) {
    #ifdef DEBUG
    pc.printf("Message Received\r\n");
    #endif
    
    int key;
    int velocity;
    
    switch (message.type()) {
        case MIDIMessage::NoteOnType:
            key = message.key();
            velocity = message.velocity();
            
            audioEngine.midiNoteOn(key, velocity);
            
            ledController.identifyKeyForLed(key, 1);
        
            #ifdef DEBUG
            pc.printf("\tType: Note On\r\n");
            pc.printf("\tNote: %d\tVelocity: %d\r\n", key, velocity);
            #endif
            break;
        case MIDIMessage::NoteOffType:
            key = message.key();
            velocity = message.velocity();
            
            audioEngine.midiNoteOff(key);
            
            ledController.identifyKeyForLed(key, -1);
        
            #ifdef DEBUG
            pc.printf("\tType: Note Off\r\n");
            pc.printf("\tNote: %d\r\n", key);
            #endif
            break;
        default:
            // no-op
            break;
    }
}

void nextSynthPressed() {
    #ifdef DEBUG
    pc.printf("Toggling to next synthesizer.r\n");
    #endif
   
    int nextIndex = audioEngine.nextSynth(1);
    my_leds(nextIndex + 1);
}

void prevSynthPressed() {
    #ifdef DEBUG
    pc.printf("Toggling to previous synthesizer.r\n");
    #endif
    
    int nextIndex = audioEngine.nextSynth(-1);
    my_leds(nextIndex + 1);
}