usb vritual serial to uart

Dependencies:   BufferedSerial USBDevice mbed

Fork of USB2UART by Yihui Xiong

main.cpp

Committer:
swxu
Date:
2017-05-19
Revision:
6:40182fd79c75
Parent:
5:10fccccbbb11
Child:
7:630d09697776

File content as of revision 6:40182fd79c75:

/**
 * USB to UART Bridge
 */
 
#include "mbed.h"
#include "USBSerial.h"
#include "BufferedSerial.h"

Ticker txrx_ticker;
Ticker state_ticker;
Ticker reset_ticker;

volatile bool rxflag = false;
volatile bool txflag = false;
volatile int rx_count = 0;
volatile int tx_count = 0;

DigitalOut tx_indicator(P0_20);
DigitalOut rx_indicator(P0_21);
DigitalOut state_indicator(P0_11);
DigitalOut cc3200_reset(P0_2);
DigitalIn reset_button(P0_1, PullUp);

USBSerial vcom;
BufferedSerial uart(P0_19, P0_18, 512);

void update_txrx_indicator()
{
    if (txflag) {
        tx_indicator = !tx_indicator;
        rxflag = false;
    } else { // TX done
        if (!tx_indicator) {
            tx_indicator = 1;
        }
    }
    
    if (rxflag) {
        rx_indicator = !rx_indicator;
        rxflag = false;
    } else { // RX done
        if (!rx_indicator) {
            rx_indicator = 1;
        }
    }
}

void update_state_indicator()
{
    state_indicator = 0;
}

void check_reset_button()
{
    if (!reset_button.read()) {
        cc3200_reset = 0;
        state_indicator = 0;
    }
}

// Called by ISR
void settings_changed(int baud, int bits, int parity, int stop)
{
    static const Serial::Parity parityTable[] = {Serial::None, Serial::Odd, Serial::Even, Serial::Forced0, Serial::Forced1};
    
    state_indicator = 1;
    if (stop != 2) {
        stop = 1;   // stop bit(s) = 1 or 1.5
    }
    uart.baud(baud);
    uart.format(bits, parityTable[parity], stop);
    state_indicator = 0;
}

int main()
{
    vcom.attach(settings_changed);
    state_ticker.attach(update_state_indicator, 0.3);
    txrx_ticker.attach_us(update_txrx_indicator, 10*1000);
    reset_ticker.attach_us(check_reset_button, 20*1000);

    while (1) {
        while (vcom.readable()) {
            char c = vcom.getc();
            tx_count++;
            txflag = true;
            uart.putc(c);
        }
        while (uart.readable()) {
            char c = uart.getc();
            rx_count++;
            rxflag = true;
            vcom.putc(c);
        }
    }
}