c++ – Controlling the device from a computer via a COM port on Windows


Good day,

I need to implement a control program for the E7-25 device. This device is connected to a computer via a usb cable, and when connected, a virtual com port is created. I can connect to this port, I checked data transmission and data reception using the Virtual Serial Port Driver, and data is sent and transmitted, but when sending data to the device in the form: char data [] = "(0xAA, 14)"; the device does not respond at all.

Here is my program code

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

HANDLE hSerial;

void ReadCOM()
      DWORD iSize;
      char sReceivedChar[20];
      while (true)
            ReadFile(hSerial, &sReceivedChar, 20, &iSize, 0);
            if (iSize > 0)
                cout << sReceivedChar;

int _tmain(int argc, _TCHAR* argv[])
    LPCTSTR sPortName = L"COM4";  

            cout << "serial port does not exist.\n";
        cout << "some other error occurred.\n";

    DCB dcbSerialParams = {0};
    if (!GetCommState(hSerial, &dcbSerialParams))
        cout << "getting state error\n";
    if(!SetCommState(hSerial, &dcbSerialParams))
        cout << "error setting serial port state\n";
    char data[] = "(0xAA, 64)";
    DWORD dwSize = sizeof(data);
    DWORD dwBytesWritten;

    BOOL iRet = WriteFile (hSerial,data,dwSize,&dwBytesWritten ,NULL);

    cout << dwSize << " Bytes in string. " << dwBytesWritten << " Bytes sended. " << endl;

    return 0;

The documentation for the device says that commands should be sent to it in the following format Exchange format:

ПК — E7-25: 0xAA, №команды, [параметры].
Е7-25 — ПК: 0xAA, №команды, [параметры].

That is, this is what the command that I send by default should return

    64 – Получить имя прибора
    ПК — (0xAA, 64); E7-25 — (0xAA, 64, “Е725”)

So I have questions. Am I sending data to the port correctly? And am I receiving them correctly from the port? Thanks in advance.


Your communication protocol with the device is obviously binary, you brought it yourself. Then, for some reason, you counted the binary data as a string, and then added two more bytes of parentheses plus a zero byte at the end on the sides:

char data[] = "(0xAA, 64)"; // эквивалентно: char data[11] = {'(', '0', 'x', 'A', 'A', ',', ' ', '6', '4', ')', 0x00}

Why was this done? It might be worth learning the syntax. It is necessary to form an array of these two bytes so that there is nothing superfluous

char data[2] = {0xAA, 64};
DWORD dwSize = 2;
// ...

Then just send these two bytes to the device.

Scroll to Top