串口通信C程序
//Set CommTimeOuts
BOOL SetCommTimeOuts ( VOID )
{
//SetComm Input & Output Buffer
SetupComm ( hSerial ,MAXLEN * 2 ,MAXLEN * 2 );
//Read TimeOut
TimeOuts.ReadIntervalTimeout = MAXDWORD; //Set Total Read TimeOut as MAXDWORD (0xFFFFFFFF)
TimeOuts.ReadTotalTimeoutConstant = 0; //Read TimeOut Const
TimeOuts.ReadTotalTimeoutMultiplier = 0; //Return Riht now
//Write TimeOut
TimeOuts.WriteTotalTimeoutMultiplier = 50; //TotalTimeOut = TimeAgr*NumOfChars+const time
TimeOuts.WriteTotalTimeoutConstant = 2000; //Set Write TimeOuts
return ( FALSE != SetCommTimeouts ( hSerial,&TimeOuts ) );
}
//Error MsgBox
BOOL ErrMsg ( HWND hWnd,TCHAR *szErr )
{
return ( FALSE != MessageBox ( hWnd,szErr,NULL,MB_OK | MB_ICONWARNING ) );
}
//Read Comm
BOOL ReadCom ( HWND hSet,BYTE InBuff[],INT BytesNum )
{
DWORD dwBytesRead = 0; //Record The bytes already read
INT iBytesToRead = 0;
DWORD dwErrMask = 0;
//Clear Memory
ZeroMemory ( &ComState ,sizeof(ComState) );
ZeroMemory ( &OvLap ,sizeof(OvLap) );
OvLap.Offset = 0;
OvLap.OffsetHigh = 0;
OvLap.hEvent = CreateEvent (NULL,TRUE,FALSE,NULL);
//Clear All sPort error
ClearCommError (hSerial,&dwErrMask,&ComState);
//Get The Bytes to read from buff
iBytesToRead = min (2000,ComState.cbInQue);
if ( 0 == iBytesToRead )
return FALSE;
else;
if ( FALSE == ReadFile (hSerial,InBuff,iBytesToRead,&dwBytesRead,&OvLap ) )
{
if ( GetLastError () == ERROR_IO_PENDING )
{
WaitForSingleObject (OvLap.hEvent,2000);
PurgeComm (hSerial,PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR );
}
else;
}
else;
return (TRUE);
}
///Write Comm
BOOL WriteCom ( BYTE *szBuff,DWORD dwBytes )
{
DWORD dwErrMask = 0 ;
DWORD dwBytesWritten = 0;
ZeroMemory ( &OvLap ,sizeof(OvLap) );
ZeroMemory ( &ComState,sizeof(ComState) );
OvLap.Offset = 0;
OvLap.OffsetHigh = 0;
OvLap.hEvent = CreateEvent (NULL,TRUE,FALSE,NULL);
//Clear All sPort error
ClearCommError (hSerial,&dwErrMask,&ComState);
if ( FALSE == WriteFile ( hSerial,szBuff,dwBytes,&dwBytesWritten ,&OvLap ) )
{
if ( GetLastError () == ERROR_IO_PENDING )
{
WaitForSingleObject (OvLap.hEvent,2000) ;
PurgeComm (hSerial,PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR );
}
else;
}
else;
return ( dwBytesWritten == dwBytes );
}
TCHAR* Caps ( TCHAR *szStr )
{
UINT i = 0;
for ( i = 0 ; szStr[i] != '\0'; i ++ )
{
if ( szStr[i] >= 'A' && szStr[i] <= 'Z' )
szStr[i] += 0x20;
}
return szStr;
}