Working with COM port in windows and linux

Working with COM port in windows and linux
Once upon a time I was making an application that was supposed to run from Windows and Linux and connect to the board with STM32 via UART. This article can be useful for beginners who program in C ++ (use the compilers GCC and MinGW) and who need COM port support under two OSes at once, and which laziness to google and you need ready-made code.
here . To connect to your project, you need to add just two files: xserial.cpp and xserial.hpp .
Example of using [/b]
#include "xserial.hpp"
using namespace std;
int main () {
/* initialize the available COM port, without checking the parity bit,
with 8-bit data bits and one stop bit. * /
const int baudRate = 115200; //port speed
const int dataBits = 8; //the length of the data is
xserial :: ComPort serial (
.xserial :: ComPort :: COM_PORT_NOPARITY,
.xserial :: ComPort :: COM_PORT_ONESTOPBIT);
if (! serial.getStateComPort ()) {//If the port did not open
cout "Error: com port is not open!" endl;
return 0;
//output the list of available ports
serial.printListSerialPorts ();
//get the text before the symbol n
cout "Test getLine () " endl;
serial "Test 1n";
cout serial.getLine () endl;
//check the function of checking the number of bytes received
cout "Test bytesToRead () " endl;
serial.print ("Test 2n");
int k = serial.bytesToRead ();
cout "bytes to read =" k endl;
while (k < 6) {
.k = serial.bytesToRead ();
.cout "bytes to read =" k endl;
//check the read function
char data[512];
.cout "Test read () "endl; (data, 7);
.cout data endl;
//check the function of reading the word
serial.print (" Bla Bla Blan ");
cout "Test getWord (), print Bla Bla Bla" endl;
cout "word 1:" serial.getWord () endl;
cout "word 2:" serial.getWord () endl;
cout "word 3 : "serial.getWord () endl;
return 0;

The class also added the function getListSerialPorts to get a list of available COM ports.
Nuances of using COM port
Under Windows, there may be problems when writing to the COM port if the Nucleo STM32 board is used as the USB-UART adapter. Often the problem occurs after the port is reinitialized, sometimes it only helps reboot the laptop.
It is assumed that anyone who needs to "google" the code can now simply download something already working and continue to use in their small project, to change for themselves, as they please.
+ 0 -

Add comment