0

我正在制作 Windows 控制台应用程序以通过 COM 端口写入和读取数据。但是,我无法发送和接收任何数据,尽管 COM 端口已成功打开。

“打开 COM 端口”代码:

unsigned int c;
LPCWSTR portCom;
TCHAR ComString[30];
HANDLE hComm;
DCB port;


int main(int argc, char* argv[])
{
// Open COM port  
        _stprintf_s(ComString, 11, _T("\\\\.\\COM3"));

        hComm = CreateFile(ComString, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

    if (hComm == INVALID_HANDLE_VALUE)
    {
        abort();
    }

    memset(&port, 0, sizeof(port));
    port.DCBlength = sizeof(port);

    if (!::GetCommState(hComm, &port))
    {
        abort();
    }
    
    port.BaudRate = CBR_115200;
    port.ByteSize = 8;
    port.Parity = NOPARITY;
    port.StopBits = ONESTOPBIT;

    if (!::SetCommState(hComm, &port))
    {
        abort();
    }

“发送和接收数据”代码:

// Send and receive data 
    unsigned char sendData[8];
    unsigned int rcvData = 0;
    DWORD dwWritten;
    DWORD dwRead;
    sendData[0] = 'A';

    WriteFile(hComm, &sendData[0], 1, &dwWritten, NULL);

    dwRead = 0;
    while (dwRead == 0) {
        ReadFile(hComm, &rcvData, 1, &dwRead, NULL);
    }
    return 0;
}
4

1 回答 1

0

我解决了我的问题。我发现使用 CreateFas 0 打开 COM 端口时需要设置 FLAG。谢谢大家。

于 2020-11-04T08:12:00.893 回答