Source code for a MIDI controller built from parts and designed to be extensible

Dependencies:   USBMIDI mbed

Fork of USBMIDI_HelloWorld by Simon Ford

main.cpp

Committer:
earlz
Date:
2016-01-04
Revision:
2:012e56772666
Parent:
1:1e34feaa7774

File content as of revision 2:012e56772666:

// Hello World example for the USBMIDI library

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

void show_message(MIDIMessage msg) {
    switch (msg.type()) {
        case MIDIMessage::NoteOnType:
            printf("NoteOn key:%d, velocity: %d, channel: %d\n", msg.key(), msg.velocity(), msg.channel());
            break;
        case MIDIMessage::NoteOffType:
            printf("NoteOff key:%d, velocity: %d, channel: %d\n", msg.key(), msg.velocity(), msg.channel());
            break;
        case MIDIMessage::ControlChangeType:    
            printf("ControlChange controller: %d, data: %d\n", msg.controller(), msg.value());
            break;
        case MIDIMessage::PitchWheelType:
            printf("PitchWheel channel: %d, pitch: %d\n", msg.channel(), msg.pitch());
            break;
        default:
            printf("Another message\n");
    }    
}

static const int MIDI_MAX_VALUE = 16384;
static const float MIDI_MAX_VALUE_F = 16384.0f;


static const float TOLERANCE = 0.01f;
static const int NOISE_FLOOR = 600;

static const float LOWER_TOLERANCE = 0.016f;
static const float LOWER_TOLERANCE_BEGIN = 0.34f;

USBMIDI midi;
AnalogIn pot1(p20);
Serial pc(USBTX, USBRX); // tx, rx

void write_full_cc(int controlmsb, int controllsb, int channel, int value){
    int lsb = value / 128; //value & 0x7F;
    int msb = value % 128; //value & 0x7F80 >> 7;
    midi.write(MIDIMessage::ControlChange(controlmsb, msb, channel));
    midi.write(MIDIMessage::ControlChange(controllsb, lsb, channel));
}

#define SMOOTHING_AMOUNT 500

int main() {       
    midi.attach(show_message);         // call back for messages received    
    
    float last_value  = 0.0f;
    while (1) {   
        float counter=0.0f;
        for(int i=0;i<SMOOTHING_AMOUNT;i++){
            wait_us(10);
            counter+=pot1;
        }
        float value = counter / SMOOTHING_AMOUNT;
        int midi_value = (int)(MIDI_MAX_VALUE_F * value);
        
        //at low voltage noise takes over..
        if(midi_value < NOISE_FLOOR){
            value = 0.0f;
            midi_value = 0;
        }
        if(value - last_value > TOLERANCE || value - last_value < -TOLERANCE){
            //as we approach noise floor, things get noisey.. 
            if(value < LOWER_TOLERANCE_BEGIN && !(value - last_value > LOWER_TOLERANCE || value - last_value < -LOWER_TOLERANCE)){
                continue;
            }
            pc.printf("sent: %f, %i\r\n", value, midi_value);
            last_value = value;
            write_full_cc(20, 52, 0, midi_value);
       }
        
    }
}