[英]C++ Communication via COM Port
How can one communicate with a device via a COM port with C++?如何通过带有 C++ 的 COM 端口与设备通信? Is there a windows library which handles this?
是否有处理此问题的 windows 库?
Thanks in advance.提前致谢。
EDIT: Im using Windows.编辑:我使用 Windows。
You can use the general file I/O API calls such as CreateFile()
and ReadFile()
to accomplish this.您可以使用通用文件 I/O API 调用,例如
CreateFile()
和ReadFile()
来完成此操作。 Additional calls such as GetCommState()
and SetCommState()
can be used to change the various settings of the serial port once it has been opened. GetCommState()
和SetCommState()
等附加调用可用于在串行端口打开后更改其各种设置。
HANDLE hSerial;
hSerial = CreateFile(
"COM1",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if(hSerial==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND)
{
//serial port does not exist. Inform user.
}
//some other error occurred. Inform user.
}
DCB dcbSerialParams = {0};
dcbSerial.DCBlength=sizeof(dcbSerialParams);
if (!GetCommState(hSerial, &dcbSerialParams))
{
//error getting state
}
dcbSerialParams.BaudRate=CBR_19200;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams))
{
//error setting serial port state
}
A lot of sample code on the web if you Google.如果你谷歌的话,web 上有很多示例代码。 Here's one example: http://members.ee.net/brey/Serial.pdf
这是一个例子: http://members.ee.net/brey/Serial.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.