im trying my hand at reading data via serial communications on a windows 32bit computer. ive accomplished this, extremely crudely and have to some degree been successful. the device i am trying to read sends data in the format $A.B.C$ followed by a '\n' or newline. using the code written below, the data is read correctly most of the time but is sometimes followed by a sequence like this:
$A.B.C$
$A.B.C$
$A.B.C$
$A.B.
C$
$
A.B.C$
basically it reads data pretty weirdly. any suggestions are accepted.thank you!
#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;
}
while (1){
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
puts ("serial read error fail!");
return;
}
else
{
printf ("%s\n" , szBuff);
}
}
getch();
return 0;
}