Code:
main(){
unsigned short SIZEIN = 2, DLE_SYN_Read_Count = 0;
char INBUFFER[20];
char inbuff[2];
char OUTBUFFER[2] = {DLE, SYN} ;
DWORD bytes_read = 0; // Number of bytes read from port
DWORD bytes_written = 0; // Number of bytes written to the port
HANDLE comport = NULL; // Handle COM port
int bStatus, i=0;
size_t result = 0;
char bufferOUT[10] = {SOH,4,251,STX,0xDE,0xAD,0xBE,0xEF,ETX,34};
DCB comSettings; // Contains various port settings
COMMTIMEOUTS CommTimeouts;
CString Par_comport;
Par_comport = "COM8";
SYSTEMTIME systemTime_Start, systemTime_End;
// Open COM port
if ((comport =
CreateFile(Par_comport, // open com5:
GENERIC_READ | GENERIC_WRITE, // for reading and writing
0, // exclusive access
NULL, // no security attributes
OPEN_EXISTING,
0,
NULL)) == INVALID_HANDLE_VALUE)
{
printf("Error: COM port Open\n");
}
GetCommState(comport, &comSettings);
comSettings.BaudRate = 115200;
comSettings.StopBits = ONESTOPBIT;
comSettings.ByteSize = 8;
comSettings.Parity = NOPARITY;
comSettings.fParity = FALSE;
comSettings.fDtrControl = TRUE;
comSettings.fRtsControl = TRUE;
bStatus = SetCommState(comport, &comSettings);
if (bStatus == 0)
{
printf("Error: COM port settings\n");
}
while(1)
{
bStatus = ReadFile(comport, // Handle
INBUFFER, // Incoming data
SIZEIN, // Number of bytes to read
&bytes_read, // Number of bytes read
NULL);
if (bStatus == 0)
{
printf("Error: Read File\n");
}
else if((INBUFFER[0]==DLE)&&(INBUFFER[1]==SYN))
{
printf("synchronize Received\n");
}
else
{
Sleep(1000);
continue;
}
break;
}
while(1)
{
if(DLE_SYN_Read_Count <= 2)
{
bStatus = WriteFile(comport, // Handle
&OUTBUFFER, // Outgoing data
2, // Number of bytes to write
&bytes_written, // Number of bytes written
NULL);
if (bStatus == 0)
{
printf("Error: Write File\n");
}
}
Sleep(1000);
bStatus = ReadFile(comport, // Handle
INBUFFER, // Incoming data
2, // Number of bytes to read
&bytes_read, // Number of bytes read
NULL);
if (bStatus == 0)
{
printf("Error: Read File\n");// error processing code goes here
}
if((INBUFFER[0]==DLE)&&(INBUFFER[1]==SYN))
{
DLE_SYN_Read_Count++;
if(DLE_SYN_Read_Count == 5)
{
break;
}
}
continue;
}
printf("synchronize Completed\n");
getch();
bStatus = WriteFile(comport, // Handle
&bufferOUT, // Outgoing data
10, // Number of bytes to write
&bytes_written, // Number of bytes written
NULL);
if (bStatus == 0)
{
printf("Error: Write File\n");
}
Sleep(1000);
bStatus = ReadFile(comport, // Handle
inbuff, // Incoming data
2, // Number of bytes to read
&bytes_read, // Number of bytes read
NULL);
printf("bStatus = %d\tbytes_read = %d\t%d\t%d\n",bStatus,bytes_read,inbuff[0],inbuff[1]);
if (bStatus == 0)
{
printf("Error: Read File\n");
}
if((inbuff[0]==DLE)&&(inbuff[1]==ACK))
{
printf("ACK Received\n");
}
else if((inbuff[0]==DLE)&&(inbuff[1]==NAK))
{
printf("NAK Received\n");
}
else
printf("Receiption of ACK fault\n%d\t%d\n",inbuff[0],inbuff[1]);
CloseHandle(comport);
getch();
return 0;
}
The last ReadFile function always get some other values in its buffer.