简体   繁体   中英

C++ Communication via COM Port

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://members.ee.net/brey/Serial.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM