I'm trying to use a Linux serial port (say /dev/ttyx) as a sting stream in C++. Just like std::cout is used.
Do you have experience with it, or do you know a decent example?
I'm trying to use a Linux serial port (say /dev/ttyx) as a sting stream in C++. Just like std::cout is used.
Do you have experience with it, or do you know a decent example?
Interesting question. I've not worked in this area, and don't have an example. However, I saw this:
https://www.nuget.org/packages/crozone.SerialPorts.LinuxSerialPort
It's quite old code. But am wondering if there is useful stuff there that could be resurrected as a serial port class with stream methods for accessing.
EDIT: forget that. I just peeked at the code, it's C# : (
EDIT 2: Looks like Qt supports streaming access: https://doc.qt.io/qt-6/qserialport.html
Don't know if you wish to add that much middleware to your app though.
There are other serial port stream implementations but they seem to be in other languages like Java : (
Threw something together quick, I didn't have time to test it, but give it a try:
https://gist.github.com/03vmate/dbd3d423bc033367ae24faa6a6616860
Use it like this:
SerialStream serial("/dev/ttyX", 9600);
// Write a string to the serial port
serial << "AT\n\r";
// Read a line from the serial port
std::cout << "Response: " << serial << std::endl;
// Read a line, in a different way
std::string response;
serial >> response;
std::cout << "Response: " << response << std::endl;
That looks very promising.
I found something that I will also test out: https://stackoverflow.com/a/24992028
#ifndef DEVTTY #define DEVTTY "con" // on Windows // #define DEVTTY "/dev/tty" // on Linux/MacOS #endif using namespace std; int main() { cout << "DEVTTY = " << DEVTTY << endl; printf("Print[f]ed to stdout.\n"); fprintf(stdout, "Print[f]ed to stdout.\n"); cout << "Printed to std::cout" << endl; fprintf(stderr, "Print[f]ed to stderr.\n"); cerr << "Printed to std::cerr" << endl; { // C, stdio version FILE* fd = fopen(DEVTTY, "w"); fprintf(fd, "Printed to \"%s\"\n", DEVTTY); // will not be redirected fclose(fd); } { // C++, fstream version std::ofstream ofs(DEVTTY); ofs << "Printed via std::ofstream to \"" << DEVTTY << "\"" << endl; // will not be redirected } return EXIT_SUCCESS; }