C++ Communication via COM Port
12,865
Solution 1
A lot of sample code on the web if you Google. Here's one example: http://members.ee.net/brey/Serial.pdf
Solution 2
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
}
Author by
JonaGik
Updated on June 04, 2022Comments
-
JonaGik almost 2 years
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.