In C++ it's common to stream data. You write to a file using the << operator. You read with >>.
example:
cout << "hello, world! << endl;
In this blog I'm making my own minimal in, out and in-out stream class for Pico UART.
I put embedded friendly in the title because this is a resource-friendly exercise. Can be used on the smallest controllers.
How would your code look like?
You 'd stream data to UART with <<
uartiostream u; u << "hello element14!\n" ; and stream from UART with >>
std::string s; u >> s;An example that first streams a constant string. Then echos everything you type in a serial monitor:
#include <string>
int main() {
// ... usual Pico UART enable
// c++ stream example
uartiostream u;
u << "hello element14!\n" ;
while (true) {
std::string s;
u >> s;
u << s;
}
}
Pico UART Stream classes: in, out and io

The code for the stream classes is surprisingly simple.
class uartostream {
public:
uartostream() {}
uartostream& operator << (const char* msg) {
uart_puts(UART_ID, msg);
return *this;
}
uartostream& operator << (const std::string& msg) {
uart_puts(UART_ID, msg.c_str());
return *this;
}
};
class uartistream {
public:
uartistream() {}
uartistream& operator >> (std::string& msg) { // blocking
char c = 0;
do {
c = uart_getc(UART_ID);
if (c != 255) {
msg += c;
}
} while (c != '\n');
return *this;
}
};
class uartiostream: public uartistream, public uartostream {
};
These classes are small in code size. And small in runtime resource use. Using them is similar for the Pico as calling the API uart_puts() and uart_getc() functions.
In essence: 30 lines of source code to get the streaming abstraction. And no runtime (memory, clock ticks, code size) overhead.
Thoughts?







