Test of Freescale K64F serial communication. Input from bluetooth module is echoed to PC USB-serial connection.

Dependencies:   mbed

main.cpp

Committer:
Mr_What
Date:
2015-08-17
Revision:
0:c571c0b21eb7

File content as of revision 0:c571c0b21eb7:

#include "mbed.h"

DigitalOut myled(LED_GREEN);
Serial PC(USBTX, USBRX);
Serial BT(PTC15, PTC14);  // for Bluetooth module header

#define RINGBUF
#ifdef RINGBUF
#define CMDBUFLEN 128
int cbuf[CMDBUFLEN];
static int bufIn=0;
static int bufOut=0;
void gotChar() {
    int c = BT.getc();
    cbuf[bufIn % CMDBUFLEN]=c;
    bufIn++;
    // prevent byte count overflow
    //   WARNING:  if there is a race and this thread resets counts...
    //              counts could look funny for a bit, but since bufIn
    //              decrements before bufOut, one hopes that the glitch will not be problematic.
    //       On race, bufIn < bufOut, they will think buffer is empty until next time
    //       they check, when count will be OK
    if (bufIn > 202*CMDBUFLEN) {
        bufIn  -= 200*CMDBUFLEN;
        bufOut -= 200*CMDBUFLEN;
    }    
}
#endif

void heartbeat() {
    static int i=0;
    PC.printf("%d \r", i++); // print the value of variable i
    myled = !myled; // toggle a led
}

int main()
{
    BT.baud(57600);   // set to match your bluetooth-serial module
    PC.baud(115200);
    //int i = 0;
    BT.printf("Hello World!\n");
    PC.puts("Ready\r");
#ifdef RINGBUF
    BT.attach(&gotChar);
#endif

    Ticker HeartBeat;
    HeartBeat.attach(heartbeat,0.8f);

    while (true) {
        wait(0.5f); // wait a small period of time

#ifdef RINGBUF
        int n = bufIn - bufOut;
        if (n>0) {
            PC.putc('\n');
            if ((n > CMDBUFLEN-3) && (n < CMDBUFLEN*180))
                PC.printf("\r\n\tserial command input overflow warning!\r\n");

            while (bufOut < bufIn) {
                int c = cbuf[bufOut % CMDBUFLEN];
                //PC.printf("\r\t%d got %d(%c)\r\n",bufOut++,c,c);
                if ((c=='\r')||(c=='\n')||(c==0)) PC.putc('\n');
                else PC.putc(c);
                bufOut++;
            }
            PC.putc('\n');
        }
#else
        int n = PC.readable();
        PC.printf("\n\n%d readable ",n);
        while(n>0) {
            int c = PC.getc();
            PC.printf("\n got %d(%c)\n",c,c);    
            n = PC.readable();
        }
#endif
    }
}