串口在Windows上读取不正确的数据

时间:2014-10-29 06:41:24

标签: c windows winapi serial-port

这个程序是通过串口接收然后发送数据。

设置序列后,从串口读取一个字节(我使用一个名为putty的工具发送字符),如果它是一个' a,从文件读取16byte然后发送连续,然后阅读''然后继续教育' p'。共有16个循环。

但是现在,我可以让前两个循环工作,当涉及第三个循环时,在readfile()之后, readBuff 是50h,而它是从串行读取的前两个循环,如' a',' b'。 它总是在第3次循环失败。

这很奇怪,有人有线索吗?

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){
        printf("create serial handle file failed!-1");
        return 0;
    }
    printf("create serial handle file failed!-2");
    return 0;
}
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
dcbSerialParams.fBinary = TRUE;
dcbSerialParams.BaudRate = CBR_9600;
dcbSerialParams.ByteSize   = 8;
dcbSerialParams.StopBits   = ONESTOPBIT;
dcbSerialParams.Parity       = NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams)){
    printf("set serial state failed");
    return 0;
}
    COMMTIMEOUTS cmt;

cmt.ReadIntervalTimeout = 1;
cmt.ReadTotalTimeoutMultiplier = 100000000;
cmt.ReadTotalTimeoutConstant = 100000000;
cmt.WriteTotalTimeoutConstant = 10;
cmt.WriteTotalTimeoutConstant = 10;

if(!SetCommTimeouts(hSerial, &cmt)){
    printf("set timeout failed");
    return 0;
}
char readBuff; //read 1 byte from serial which indicate the send loop
DWORD dwBytesRead; //number of bytes read from binary
char writeBuff[16]; /*read 16bytes from spd binary to write to serial */
DWORD dwBytesWrite; /*stores actual number of bytes writen*/
for(int i = 0; i<=15; i++){
    //initial the variables to 0 incase some weird behavior
    readBuff = 0; 
    dwBytesRead = 0;
    dwBytesWrite = 0;
    for(int j=0; j<=15; j++)
        writeBuff[j] = 0;

    if(!ReadFile(hSerial, &readBuff, 1 , &dwBytesRead, NULL)){
        if(dwBytesRead != 1){
            printf("read failed, please check!\n");
            return 0;
        }
    }
//when it comes to the 3rd loop, readfile() reads a 50h, even if i didn't send anything to serial line.
    if(readBuff != ('a' + i)){
        printf("failed the %dth loop\n", i);
        return 0;
    }
    else{
        //read spd binary then puts to serial

        if(fread(writeBuff, 1, 16, file) != 16){
            printf("read binary failed, please check!\n");
            return 0;
        }
        //send to serial
        if(!WriteFile(hSerial, writeBuff, 16, &dwBytesWrite, NULL)){
            if(dwBytesWrite != 16){
                printf("write to serial failed, please check!\n");
                return 0;
            }
        }
        printf("%c", readBuff);

    }
}//end of for loop

1 个答案:

答案 0 :(得分:2)

如果ReadFile失败,您需要再次阅读,直到找到一些有效数据。但相反,您检查dwBytesRead并根据该变量中的内容做出继续决定。当ReadFile失败时,我不相信dwBytesRead包含有效值。假设UART读取1个字节但是出现了溢出/帧错误?

将程序更改为

   while(!ReadFile(...))
     ;