windows 通过 COM 端口的 C++ 通信
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7035294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Communication via COM Port
提问by JonaGik
How can one communicate with a device via a COM port with C++? Is there a windows library which handles this?
如何使用 C++ 通过 COM 端口与设备通信?是否有处理此问题的 Windows 库?
Thanks in advance.
提前致谢。
EDIT: Im using Windows.
编辑:我使用 Windows。
采纳答案by jcomeau_ictx
A lot of sample code on the web if you Google. Here's one example: http://members.ee.net/brey/Serial.pdf
如果你谷歌,网上有很多示例代码。这是一个例子:http: //members.ee.net/brey/Serial.pdf
回答by Captain Obvlious
You can use the general file I/O API calls such as CreateFile()
and ReadFile()
to accomplish this. Additional calls such as GetCommState()
and SetCommState()
can be used to change the various settings of the serial port once it has been opened.
您可以使用诸如CreateFile()
和 之类的通用文件 I/O API 调用ReadFile()
来完成此操作。诸如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
}