Simple USB-MIDI foot controller

Dependencies:   PinDetect USBDevice_STM32F103 mbed-STM32F103C8T6

main.cpp

Committer:
SpotlightKid
Date:
2017-07-31
Revision:
1:61415f07477d
Parent:
0:2f530d7169a6
Child:
3:8b8cb5392fa0

File content as of revision 1:61415f07477d:

#include "stm32f103c8t6.h"
#include "mbed.h"
#include "USBMIDI.h"
#include "PinDetect.h"

#define SWITCH1_PIN PB_5
#define LED_DURATION 20000

USBMIDI *midi;
Serial *serial;
DigitalOut *led1;
int led_ontime;
Timer *timer;

class SwitchHandler {
public:
    explicit SwitchHandler(uint8_t ctrl, uint8_t ch = 1, uint8_t on = 0, uint8_t off = 127) :
        control(ctrl), channel(ch), on_value(on), off_value(off), b_pressed(false), b_released(false) {
    };
    
    void handle_pressed(void) {
        b_pressed = true;
    }

    void handle_released(void) {
        b_released = true;
    }

    void handle_events() {
        if (b_pressed) {
            led1->write(0);
            led_ontime = timer->read_us();
            serial->printf("Switch pressed: controller=%d channel=%d value=%d\r\n", control, channel, on_value);
            midi->write(MIDIMessage::ControlChange((int) control, (int) on_value, (int) (channel - 1)));
            b_pressed = false;
        } else if (b_released) {
            led1->write(0);
            led_ontime = timer->read_us();
            serial->printf("Switch released: control=%d channel=%d value=%d\r\n", control, channel, off_value);
            midi->write(MIDIMessage::ControlChange((int) control, (int) off_value, (int) (channel - 1)));
            b_released = false;
        }
    }
private:
    uint8_t control, channel, on_value, off_value;
    bool b_pressed, b_released;
};

int main() {
    // Configure system clock (72MHz HSE clock, 48MHz USB clock)
    confSysClock();

    timer = new Timer;
    led1 = new DigitalOut(LED1);
    led1->write(1);
    serial = new Serial(PA_9, PA_10);
    midi = new USBMIDI(0x1f00, 0x2012, 0x0001);
    SwitchHandler handler1(1, 10);

    PinDetect btn(SWITCH1_PIN);
    btn.attach_asserted(&handler1, &SwitchHandler::handle_pressed);
    btn.attach_deasserted(&handler1, &SwitchHandler::handle_released);
    btn.setSampleFrequency();
    timer->start();

    while (true) {
        handler1.handle_events();
        wait_ms(10);
        if (timer->read_us() - led_ontime >= LED_DURATION) {
            led_ontime = 0;
            led1->write(1);
        }   
   }
}