Receiving information via com port c. Serial Port Monitor COM Port Monitoring Software

Serial ports are loved by developers for their ease of maintenance and use.

And of course, writing to the console of a terminal program is all well and good, but you want your own application, which, when you press a key on the screen, performs the actions you need;)

In this article I will describe how to work with com port in C++ language.

The solution is simple, but for some reason a working example was not found immediately. So I’m saving it here.

Of course, you can use cross-platform solutions like QSerial - a library included in Qt, I will probably do so, but in the future. Now we are talking about “pure” Windows C++. We will write in Visual Studio. I have 2010, although this doesn’t matter at all...

Create a new Win32 console project.

Include header files:

#include #include using namespace std;

We declare a com port handler:

HANDLE hSerial;

I do this globally so as not to bother with pointers when passing it to functions.

Int _tmain(int argc, _TCHAR* argv) (

I can't stand the Windows style of programming. They called everything their own name and sat there rejoicing...

Now the magic of declaring a string with the name of the port. The fact is that it cannot convert char itself.

LPCTSTR sPortName = L"COM1";

Working with serial ports in Windows works like a file. Opening the first one com port for writing/reading:

HSerial = ::CreateFile(sPortName,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);

Checking functionality:

If(hSerial==INVALID_HANDLE_VALUE) ( if(GetLastError()==ERROR_FILE_NOT_FOUND) ( cout