Test program using serial in RTOS

Dependencies:   EthernetInterface mbed-rtos mbed

main.cpp

Committer:
Cypress
Date:
2015-09-24
Revision:
0:30562abde493

File content as of revision 0:30562abde493:

#include "main.h"

char rxBuffer[BUF_LEN];
int rxChars;
bool rxDone;
long rxTime;
RtosTimer *rxTimer;

char txBuffer[BUF_LEN];
int txChars;

Serial sp(SP_RX, SP_TX);
EthernetInterface eth;
TCPSocketServer serv;
TCPSocketConnection client;

int main ( void )
{
    // Initalize serial port
    sp.baud(SP_BAUD);
    sp.attach(&rxInt);
    rxTimer = new RtosTimer(&timerTask, osTimerPeriodic, NULL);
    rxTimer->start(SP_TIMER_PERIOD);
    
    // Initalize server
    serv.bind(SERV_PORT);
    serv.listen();
    while (true)
    {
        serv.accept(client);
        client.set_blocking(false, 1500);
        
        while (client.is_connected())
        {
            txChars = client.receive(txBuffer, BUF_LEN);
            if (txChars <= 0) break;
            
            sendBuffer(txBuffer, txChars);
        }
        client.close();
    }
}

void timerTask ( void const *arg )
{
    if (!rxDone)
    {
        if (client.is_connected())
        {
            client.send_all(rxBuffer, rxChars);
            resetRX();
        }
    }
    else
    {
        if (rxChars > 0)
        {
            if (rxTime++ >= SP_TIMEOUT) rxDone = true;
        }
    }
}

void rxInt ( void )
{
    if (!rxDone)
    {
        if (rxChars < BUF_LEN)
        {
            rxBuffer[rxChars++] = SP_UART->D;
            rxTime = 0;
        }
        else rxDone = true;
    }
}

void sendBuffer (char *buffer, int len)
{
    for (int i = 0; i < len; i++)
    {
        sp.putc(buffer[i]);
    }
}

void clearBuffer ( char *buffer, int len )
{
    for (int i = 0; i < len; i++) buffer[i] = 0;
}

void resetRX ( void )
{
    clearBuffer(rxBuffer, BUF_LEN);
    rxChars = 0;
    rxDone = false;
}

void resetTX ( void )
{
    clearBuffer(txBuffer, BUF_LEN);
    txChars = 0;
}