![](/media/cache/profiles/d3b154a6afe99c7d4f2b3fa23962a134.jpg.50x50_q85.png)
testing functionalities of serial over USB
Diff: main.cpp
- Revision:
- 1:a00097bc510b
- Parent:
- 0:8765af830f0e
--- a/main.cpp Mon Mar 07 14:31:11 2022 +0000 +++ b/main.cpp Thu Mar 10 14:57:26 2022 +0000 @@ -1,33 +1,63 @@ #include "mbed.h" - +#define BUF_SIZE 1024 + +// attributes - peripherals +Serial pc(SERIAL_TX, SERIAL_RX); DigitalOut myled(LED1); -Serial pc(USBTX,USBRX); - -int main() -{ +Timer timeout; +Ticker blinker; - pc.baud(9600); // 8 bit No parity 1 stop - int i = 0; - char inChar; - //PC.printf("\nPress Button to enter/exit sleep & deepsleep\n"); - - // main loop - while( true ) { +// 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 something on input - while ( !pc.readable() ) { - myled = !myled; - wait(.5) + // 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 } - myled = 1; + + // 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 - fflush(stdout); - inChar=pc.getc(); // get char over serial - pc.printf ("0x%.2X", inChar); // echo HEX code - if ( inChar = '\r' ) pc.putc('\n'); // add a line feed on return - - } - - myled = 0; - + + } } \ No newline at end of file