串口通信读取功能无法读取完整响应

时间:2017-02-24 21:44:52

标签: c++ serial-port

我在发送" ATZ"后阅读完整的返回字符串时遇到问题命令我的OBDII加密狗设备中有一个STN1100芯片。以下是发送" ATZ"的回复响应。对油灰的命令:

returned string on putty

这是我的COM设置代码:

LPCWSTR port = L"COM6";

device = CreateFile(port,
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    NULL,
    0);

if (device == INVALID_HANDLE_VALUE) {
    printf("Failed to open port\n");
    printf("error code is %i\n", device);
    return false;
}
else 
    printf("Port is open successfully!\n");

//Settings
/*Timeout*/
COMMTIMEOUTS timeout;
timeout.ReadIntervalTimeout = 1;
timeout.ReadTotalTimeoutConstant = 1;
timeout.ReadTotalTimeoutMultiplier = 1;
timeout.WriteTotalTimeoutConstant = 1;
timeout.WriteTotalTimeoutMultiplier = 1; 
if (!SetCommTimeouts(serialHandle, &timeout)) {
    printf("Error setting the timeout\n");
    printf("Error code: %i\n", GetLastError());
}
/**/
DCB serialParams;
serialParams.DCBlength = sizeof(serialParams);
if (!GetCommState(device, &serialParams))  //need this getCommState before setCommState
    printf("Error getting current DCB settings\n");
serialParams.BaudRate = CBR_9600;
serialParams.ByteSize = 8;
serialParams.StopBits = ONESTOPBIT;
serialParams.Parity = NOPARITY;
serialParams.fOutX = FALSE;
serialParams.fInX = FALSE;
serialParams.fBinary = TRUE;
serialParams.fNull = TRUE;
serialParams.fRtsControl = RTS_CONTROL_DISABLE;
if (!SetCommState(device, &serialParams)) {
    printf("Error setting the DCB\n");
    printf("Error code: %i\n", GetLastError());
}

这是我的写入和读取功能:

bool Write(HANDLE device) { 
bool bErrorFlag = FALSE;
char DataBuffer[] = "ATZ\n";
//char* cmd = DataBuffer;
DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
DWORD dwBytesWritten = 0; 

bErrorFlag = WriteFile(
    device,
    DataBuffer,
    3,
    &dwBytesWritten,
    NULL);
if (!bErrorFlag) {
    printf("Failed to write to device\n");
    printf("Error code: %i\n", GetLastError());
    return false;
}
return true;
}    
bool Read(HANDLE device) {
char ReadBuffer[256] = { 0 };
int BUFFERSIZE = 256;
DWORD dwBytesRead = 0;
DWORD read;
OVERLAPPED ol = { 0 };

if (!ReadFile(device, ReadBuffer, BUFFERSIZE - 1, &read, 0))
{
    printf("Terminal failure: Unable to read from device.\n GetLastError=%08x\n", GetLastError());
    CloseHandle(device);
    return false;
}
printf("Response is %s\n", ReadBuffer);

return true;
}

我只能接收返回的echo命令" ATZ"通过运行上面的代码,有谁知道我做错了什么设置?看起来读取函数在收到第一行后停止从缓冲区读取。

0 个答案:

没有答案