TEAMUSB_SLAVE

Dependencies:   USBHost mbed

Fork of USBHostKeyboard_HelloWorld by TEAMUSB

main.cpp

Committer:
armdran
Date:
2015-04-03
Revision:
10:54ffd94e075c
Parent:
9:8bcd70b26084
Child:
11:e12aae7de530

File content as of revision 10:54ffd94e075c:

#include "mbed.h"
#include "USBHostKeyboard.h"
#include "rtos.h"

DigitalOut led(LED1);
SPISlave device(D11, D12, D13, D10);
uint8_t keyReg = 0x0;

void onKeyMod(uint8_t key, uint8_t modifier) {
    printf("Key: %x modifier: %x\r\n", key, modifier);
    keyReg = key; 
}


void keyboard_task(void const *) {
    
    USBHostKeyboard keyboard;
    
    while(1) {
        
        printf("trying to connect\r\n");
        
        // try to connect a USB keyboard
        while(!keyboard.connect()) {
            Thread::wait(500);
        }

        printf("connected\r\n");

    
        // when connected, attach handler called on keyboard event
        //keyboard.attach(onKey);
        keyboard.attach(onKeyMod);
        
        printf("eventhandler attached\r\n");
        
        // wait until the keyboard is disconnected
        while(keyboard.connected()) {
            USBHost::poll();
        }
            
        printf("disconnected\r\n");
        
    }
}

int main() {
    Thread keyboardTask(keyboard_task, NULL, osPriorityNormal, 256 * 4);
    device.frequency(1000000);
    //device.format(8, 1);
    device.format(8, 3);
    
    //while(1) {
        //Thread::wait(1000); 
        //printf("waiting...\r\n");
    //}
    
    int i = 0; 
        
    while(1) {
        
        //get instruciton
        printf("first poll\r\n");
        device.reply(0x00);
        while(!device.receive()) {
             if(i++ % 10000 == 0) {
                 printf(".");
             }
        }
        
        uint8_t instruction = device.read();
        
        if(instruction != 0xFE) {
            printf("received %x on first poll\r\n", instruction );
            continue;        
        }
        
        printf("second step\r\n");
        device.reply(keyReg);        
        
        while(!device.receive()) {
             if(i++ % 10000 == 0) {
                 printf(".");
             }
        }
        
        device.read();

        printf("third step\r\n");
        device.reply(0x00);        

        while(!device.receive()) {
             if(i++ % 10000 == 0) {
                 printf(".");
             }
        }

        int response = device.read();
            
        printf("Sent Keystroke %x over SPI. response was %x\r\n", keyReg, response);
         
        if(response == keyReg) {
            keyReg = 0;
        }
        
    }
    
}