发送文本发送到COM端口

时间:2014-02-23 15:23:01

标签: c++ windows serial-port

我有一台PLC连接到我的笔记本电脑的一个COM端口,我试图发送一个默认命令,返回默认响应。目前WriteFile成功发送了20位命令,但ReadFile没有读取任何内容,但没有错误。

int main(){

    HANDLE hCom = CreateFile("\\\\.\\COM4",
                            GENERIC_READ | GENERIC_WRITE, 
                            0, 
                            NULL, 
                            OPEN_EXISTING, 
                            0, 
                            NULL);
    if (hCom == INVALID_HANDLE_VALUE)
    {
        DWORD err=GetLastError();
        std::cout << "Failed\n";
        return 0;
    }

    DCB dcbConfig;
    if(GetCommState(hCom, &dcbConfig))
    {
        dcbConfig.BaudRate = CBR_115200;
        dcbConfig.ByteSize = 8;
        dcbConfig.Parity = NOPARITY;
        dcbConfig.StopBits = ONESTOPBIT;
        dcbConfig.fBinary = TRUE;
        dcbConfig.fParity = FALSE;
    }
    if(!SetCommState(hCom, &dcbConfig))
    {
        CloseHandle(hCom);
        return 0;
    }
    COMMTIMEOUTS commTimeout;

    if(GetCommTimeouts(hCom, &commTimeout))
    {
        commTimeout.ReadIntervalTimeout     = 1;
        commTimeout.ReadTotalTimeoutConstant     = 1;
        commTimeout.ReadTotalTimeoutMultiplier     = 1;
        commTimeout.WriteTotalTimeoutConstant     = 1;
        commTimeout.WriteTotalTimeoutMultiplier = 1;
    }
    if(!SetCommTimeouts(hCom, &commTimeout))
        //Handle Error Condition
        CloseHandle(hCom);

    // Write to the COM
    static char data[22]="%01#RDD0010000107**\n";
    int size = strlen(data);
    DWORD dwWritten, dwReading;

    int j;
    WriteFile(hCom,data,(DWORD)size,&dwWritten,NULL);
    DWORD err=GetLastError();
    std::cout << err;
    char datarecv[22];
    ReadFile(hCom,&datarecv,1,&dwReading,NULL);
    err = GetLastError();
    std::cout << err;

    std::cout << datarecv << "\n";
    CloseHandle(hCom);

    std::cin>>j;
    return 0;
}

0 个答案:

没有答案