Inherit from Serial and use software buffers for TX and RX. This allows the UART peripherals to operate in a IRQ driven mode. Overrides most (but not all) stdio functions as Serial did

Dependencies:   Buffer

Dependents:   buffered_serial_test BLE_Police_HRM evena_BLE_Police_HRM df-2014-workshop-rfid-case-generator-k64f ... more

Example

 #include "mbed.h"
 #include "BufferedSerial.h"

 BufferedSerial pc(USBTX, USBRX);

 int main()
 {
     pc.baud(115200);
   
     while(1)
     {
         Timer s;
       
         s.start();
         pc.printf("Hello World - buff\n");
         int buffered_time = s.read_us();
         wait(0.1f); // give time for the buffer to empty
       
         s.reset();
         printf("Hello World - poll\n");
         int polled_time = s.read_us();
         s.stop();
         wait(0.1f); // give time for the buffer to empty
       
         pc.printf("printf buffered took %d us\n", buffered_time);
         pc.printf("printf polled took %d us\n", polled_time);
         wait(0.5f);
     }
 }
Revision:
10:9ee15ae3d1a3
Parent:
8:506247a040bc
Child:
11:779304f9c5d2
diff -r 2cb30392ade6 -r 9ee15ae3d1a3 BufferedSerial.cpp
--- a/BufferedSerial.cpp	Sun Jan 04 23:27:53 2015 +0000
+++ b/BufferedSerial.cpp	Wed Jan 07 18:37:11 2015 +0000
@@ -23,11 +23,12 @@
 #include "BufferedSerial.h"
 #include <stdarg.h>
 
-BufferedSerial::BufferedSerial(PinName tx, PinName rx, const char* name)
-    : SERIAL_BASE(tx, rx) , _rxbuf(2*BUFFEREDSERIAL_MAX_BUFFER_SIZE), _txbuf(2*BUFFEREDSERIAL_MAX_BUFFER_SIZE)
+BufferedSerial::BufferedSerial(PinName tx, PinName rx, uint32_t buf_size, uint32_t tx_multiple, const char* name)
+    : SERIAL_BASE(tx, rx) , _rxbuf(buf_size), _txbuf((uint32_t)(tx_multiple*buf_size))
 {
     SERIAL_BASE::attach(this, &BufferedSerial::rxIrq, Serial::RxIrq);
-    
+    this->_buf_size = buf_size;
+    this->_tx_multiple = tx_multiple;   
     return;
 }
 
@@ -80,20 +81,21 @@
 
 int BufferedSerial::printf(const char* format, ...)
 {
-    memset(this->_buffer,0,BUFFEREDSERIAL_MAX_BUFFER_SIZE+1);
+    char buffer[this->_buf_size];
+    memset(buffer,0,this->_buf_size);
     int r = 0;
 
     va_list arg;
     va_start(arg, format);
-    r = vsprintf(this->_buffer, format, arg);
+    r = vsprintf(buffer, format, arg);
     // this may not hit the heap but should alert the user anyways
-    if(r > BUFFEREDSERIAL_MAX_BUFFER_SIZE) {
-        error("%s %d buffer overwrite (max_buf_size: %d exceeded: %d)!\r\n", __FILE__, __LINE__,BUFFEREDSERIAL_MAX_BUFFER_SIZE,r);
+    if(r > this->_buf_size) {
+        error("%s %d buffer overwrite (max_buf_size: %d exceeded: %d)!\r\n", __FILE__, __LINE__,this->_buf_size,r);
         va_end(arg);
         return 0;
     }
     va_end(arg);
-    r = BufferedSerial::write(this->_buffer, r);
+    r = BufferedSerial::write(buffer, r);
 
     return r;
 }