Bringing MBed serial ports back like it's 1999... or at least 2019.
Dependents: CC1200-MorseEncoder AccurateWaiter-Test
SerialStream adapts an MBed 6.0 serial port class into a Stream instance. This lets you do two useful things with it:
- Call printf() and scanf() on it
- Pass it to code that expects a Stream to print things on. This should help adapt code written for older versions of MBed with a minimum of pain.
Example code:
Hello world program with SerialStream
#include <mbed.h> #include "SerialStream.h" BufferedSerial serial(USBTX, USBRX, 115200); SerialStream<BufferedSerial> pc(serial); int main() { while(true) { pc.printf("Hello world!\n"); ThisThread::sleep_for(1s); } }
Why Serial was deprecated
Using a Stream does introduce some additional overhead into your code, and this was part of the reason the new serial classes did not implement Stream. However, this is unlikely to make a difference in many applications.
There is also a newer way to use printf() with BufferedSerial using fdopen():
Hello world program with mbed 6 serial
#include <mbed.h> BufferedSerial serial(USBTX, USBRX, 115200); FILE * pc; int main() { pc = fdopen(&serial, "r+"); while(true) { fprintf(pc, "Hello world!\n"); ThisThread::sleep_for(1s); } }
This takes advantage of Mbed's FileHandle API and its integration with the C library. Any class that implements FileHandle can be opened as a C FILE
.
This method (along with some other interesting info) can be found in the PR that deprecated Serial. In my opinion, this is something that ARM has done an atrocious job of documenting and it’s criminal that the only place I found this information was by digging through closed PRs! (though it’s also buried in the FileHandle docs if you look hard enough)
Revision 2:3736580f2dbe, committed 2020-11-12
- Comitter:
- Jamie Smith
- Date:
- Thu Nov 12 22:25:27 2020 -0800
- Parent:
- 1:9437ea7d0799
- Commit message:
- Fix access on write and read
Changed in this revision
SerialStream.h | Show annotated file Show diff for this revision Revisions of this file |
--- a/SerialStream.h Tue Aug 25 17:53:20 2020 -0700 +++ b/SerialStream.h Thu Nov 12 22:25:27 2020 -0800 @@ -1,7 +1,6 @@ #ifndef SERIALSTREAM_H #define SERIALSTREAM_H -#include <mbed.h> #include <platform/Stream.h> /** @@ -32,9 +31,6 @@ { } - -private: - // override Stream::read() and write() to call serial class directly. // This avoids the overhead of feeding in individual characters. virtual ssize_t write(const void *buffer, size_t length) @@ -47,6 +43,7 @@ return serialClass.read(buffer, length); } +protected: // Dummy implementations -- these will never be called because we override write() and read() instead. // but we have to override them since they're pure virtual. virtual int _putc(int c) { return 0; }