miniblip USB piano example

Dependencies:   USBDevice mbed

Fork of Fruit_Piano by Seeed

main.cpp

Committer:
yihui
Date:
2014-05-26
Revision:
0:4755a81efb1d
Child:
1:93bbcf91f356

File content as of revision 0:4755a81efb1d:

#include "mbed.h"
#include "USBKeyboard.h"

#define LOG(args...)        // printf(args)

#define THRESHOLD   2
#define TOUCH_N     6

BusOut leds(LED1, LED2, LED3, LED4);
Ticker tick;
USBKeyboard keyboard;

uint8_t       key_map[TOUCH_N] = {RIGHT_ARROW, LEFT_ARROW, DOWN_ARROW, UP_ARROW, ' ', '\n'};
PinName       touch_pin[TOUCH_N] = {A0, A1, A2, A3, A4, A5};
DigitalInOut *p_touch_io[TOUCH_N];

uint8_t touch_data[TOUCH_N] = {0, };

void detect(void)
{
    for (int i = 0; i < TOUCH_N; i++) {
        uint8_t count = 0;
        DigitalInOut *touch_io = p_touch_io[i];
        
        touch_io->input();
        touch_data[i] <<= 1;
        while (touch_io->read()) {
            count++;
            if (count > THRESHOLD) {
                touch_data[i] |= 0x01;
                break;
            }
        }
        touch_io->output();
        touch_io->write(1);
        
        if (0x01 == touch_data[i]) {            // a measurement is about the threshold, get a touch
            leds = 1 << i;
            keyboard.putc(key_map[i]);
            LOG("No %d key is touched\r\n", i);
        } else if (0x80 == touch_data[i]) {     // last 7 measurement is under the threshold, touch is released
            leds = 0x00;
            LOG("No %d key is released\r\n", i);
        }
    }
}

int main()
{
    // setup
    for (int i = 0; i < TOUCH_N; i++) {
        p_touch_io[i] = new DigitalInOut(touch_pin[i]);
        p_touch_io[i]->mode(PullDown);
        p_touch_io[i]->output();
        p_touch_io[i]->write(1);
    }
    
    tick.attach(detect, 1.0 / 64.0);
    
    while(1) {
        // do something
        wait(1);
    }
}