How can开发者_运维百科 one communicate with a device via a COM port with C++? Is there a windows library which handles this?
Thanks in advance.
EDIT: Im using Windows.
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.
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. Here's one example: http://web.archive.org/web/20220426073821/http://members.ee.net/brey/Serial.pdf
精彩评论