testing functionalities of serial over USB

Dependencies:   mbed

main.cpp

Committer:
ffxx68
Date:
2022-03-10
Revision:
1:a00097bc510b
Parent:
0:8765af830f0e

File content as of revision 1:a00097bc510b:

#include "mbed.h"
#define BUF_SIZE 1024
 
// attributes - peripherals
Serial pc(SERIAL_TX, SERIAL_RX);
DigitalOut myled(LED1);
Timer timeout;
Ticker blinker;
 
// attributes - program variables
char fileOverSerialBuffer[BUF_SIZE];   // buffer to store received string over pc

// local methods
void ledBlink ( void ) {
    myled != myled;
}

// main
int main() {

    int i;
    int bytesReceived = 0;

    pc.baud ( 600 ); // slow communication!
    //pc.attach(&serialDataCallback);  // attach pc ISR

    while ( true ) {

        // ready for a new file to be received
        bytesReceived = 0; 
        timeout.stop();
        timeout.reset();
        blinker.attach( &ledBlink, 1.0 );
        
        // wait for input
        while ( pc.readable() && timeout.read() < 1 ) {
                if ( bytesReceived == 0 ) {
                    timeout.start(); // watchdog 
                    timeout.reset();
                }
                if ( bytesReceived < BUF_SIZE-1 ) { // avoid buffer overflow
                    fileOverSerialBuffer[bytesReceived++] = pc.getc();
                    myled = fileOverSerialBuffer[bytesReceived] & 0x01; // show activity
                    timeout.reset(); // got byte: reset watchdog
                } else
                    break; // buffer full - stop receiving
        }

        // file completed - process
        fileOverSerialBuffer[bytesReceived+1] = '\x00'; // terminate a string
        blinker.detach(); // stop flashing
        myled = 1; // processing
        pc.printf("Got %d bytes\n\r", bytesReceived);
        for ( i=0; i < bytesReceived; i++) {
            pc.printf("%.2x ", fileOverSerialBuffer[i]);
            if ( !(i%16) && i!=0 ) pc.printf("\n\r");
        }
        pc.printf("\n\r");
        myled = 0; // done
        

    }
}