Control of the device from a computer via the COM port on Windows
Good afternoon,
I need to implement an E7-25 instrument control program. This device is connected to the 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 the 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 the code my program
#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";
hSerial = ::CreateFile(sPortName,GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if(hSerial==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND)
{
cout << "serial port does not exist.\n";
}
cout << "some other error occurred.\n";
}
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
{
cout << "getting state error\n";
}
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams))
{
cout << "error setting serial port state\n";
}
char data[] = "(0xAA, 64)";
DWORD dwSize = sizeof(data);
DWORD dwBytesWritten;
LPOVERLAPPED ov;
BOOL iRet = WriteFile (hSerial,data,dwSize,&dwBytesWritten ,NULL);
cout << dwSize << " Bytes in string. " << dwBytesWritten << " Bytes sended. " << endl;
while(1)
{
ReadCOM();
}
return 0;
}
In the documentation for the device, it is written that you need to send commands 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{[4] should return]}
64 – Получить имя прибора
ПК — (0xAA, 64); E7-25 — (0xAA, 64, “Е725”)
So I have some questions. Am I sending the data to the port correctly? And am I receiving them correctly from the port? Thank you in advance.
1 answers
The protocol of communication with the device you have - 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 on the sides, plus a null byte at the end:
char data[] = "(0xAA, 64)"; // эквивалентно: char data[11] = {'(', '0', 'x', 'A', 'A', ',', ' ', '6', '4', ')', 0x00}
Why was this done? Perhaps you should learn the syntax. You need 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.