i have a microcontroller connected to my usb port which i am reading using the code below `
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main (void)
{
int n = 25;
char szBuff[25 + 1] = {0};
HANDLE hSerial;
DCB dcbSerialParams = {0};
COMMTIMEOUTS timeouts={0};
DWORD dwBytesRead =25;
dcbSerialParams.DCBlength=sizeof(DCB);
hSerial = CreateFile("COM4",
GENERIC_READ | GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if(hSerial==INVALID_HANDLE_VALUE)
{
if(GetLastError()==ERROR_FILE_NOT_FOUND)
{
puts ("cannot open port!");
return;
}
puts ("invalid handle value!");
return;
}
if (!GetCommState(hSerial, &dcbSerialParams))
{
puts ("error getting state");
return;
}
dcbSerialParams.BaudRate=CBR_57600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=ONESTOPBIT;
dcbSerialParams.Parity=NOPARITY;
if(!SetCommState(hSerial, &dcbSerialParams))
{
puts ("error setting port state");
return;
}
timeouts.Read开发者_开发技巧IntervalTimeout = 30;
timeouts.ReadTotalTimeoutMultiplier = 100;
timeouts.ReadTotalTimeoutConstant = 100;
if (!SetCommTimeouts(hSerial, &timeouts))
{
puts ("timeouts setting fail!");
}
while (1){
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
puts ("serial read error fail!");
return;
}
else
{
printf ("%s\n" , szBuff);
}
}
getch();
return 0;
}
`
i am sending data by this format: $A.B.C$ followed by a newline. so its 7 (or 8, including newline) bytes right? i set the 3rd argument for readfile to 20, greater than 7 bytes so that i can succesfully read all of the data string. however reading sometimes misses a few characters. instead of reading $A.B.C$ i read in one line $A.B.C and in the line after that $ (a hidden'\n'). how can i fix this?
This is normal. When the receive buffer contains at least one byte, you'll get back whatever is in the buffer. Which is usually but a fraction of what you expect, serial ports are quite slow. You'll have to keep reading until you get the full response.
Just to add to the answer, be sure to use some type of timeout, or you will block waiting a character that maybe never comes.
Maybe one option could be reading byte per byte then just wait the last '$' or '\n' to know that you received the complete string and then process it.
精彩评论