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?
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; }
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; }