----串口发数据问题-----
我在向串口发数据的过程中,总是发不出去,代码如下:
// Open the serial port.
hPort = CreateFile (_T("COM1"), // Pointer to the name of the port
GENERIC_READ | GENERIC_WRITE,
// Access (read/write) mode
0, // Share mode
NULL, // Pointer to the security attribute
OPEN_EXISTING,// How to open the serial port
0, // Port attributes
NULL); // Handle to port with attribute
// to copy
。。。。。
//send data
// Specify a set of events to be monitored for the port.
SetCommMask (hPort, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING|EV_TXEMPTY|EV_RXFLAG );
PurgeComm(hPort,PURGE_RXCLEAR);
PurgeComm(hPort,PURGE_TXCLEAR);
//receive the SMS or GPS sign
while ( hPort != INVALID_HANDLE_VALUE )
{
// Wait for an event to occur for the port.
WaitCommEvent (hPort, &dwCommModemStatus, 0);
//Send the command of user
if (dwCommModemStatus & EV_TXEMPTY)
{
DWORD dwWcsLen=wcslen( tcsSmsSentData ),dwWritten=0;
if ( dwWcsLen >0 ){
__try
{
::EnterCriticalSection (&csMyCriticalSection);
BYTE *chEncode=new BYTE [ 58+dwWcsLen*4+3];
memset(chEncode,'\0',58+dwWcsLen*4+3);
chEncode[0]='\x02';
chEncode[1]='U';
BYTE byHigh,byLow;
//encode the mobile phone
for (int i=0;i<11;i++){
byHigh=HIBYTE(tcsMobilePhone[i]);
if ( HexToChar(byHigh,chEncode+2,i*4) == -1 )
break;
byLow=LOBYTE(tcsMobilePhone[i]);
if ( HexToChar(byLow,chEncode+2,i*4+2) == -1 )
break;
}
//insert the seperator symbol
chEncode[46]='0';
chEncode[47]='0';
chEncode[48]='3';
chEncode[49]='0';
//encode the SMS data
DWORD dwEncode=0;
for ( dwEncode;dwEncode<dwWcsLen;dwEncode++){
byHigh=HIBYTE(tcsSmsSentData[dwEncode]);
if ( HexToChar(byHigh,chEncode+50,dwEncode*4) == -1 )
break;
byLow=LOBYTE(tcsSmsSentData[dwEncode]);
if ( HexToChar(byLow,chEncode+50,dwEncode*4+2) == -1 )
break;
}
//append the end symbol
strcat((char*)chEncode,"000D000A");
int iEncodeLen=strlen((char*)chEncode);
BYTE *pByte=chEncode;
// iEncodeLen=strlen((char*)chEncode);
for ( i=0;i<iEncodeLen;i++){
WriteFile( hPort,
pByte++,
// chEncode,
// 58+dwWcsLen*4+2,
1,
&dwWritten,
0);
}
BYTE by=13;
WriteFile( hPort,&by,1, &dwWritten, 0);
by=10;
WriteFile( hPort,&by,1, &dwWritten, 0);
if ( dwWritten == dwWcsLen )
tcsSmsSentData[0]=L'\0';
delete []chEncode;
}
__finally
{
//退出临界区
::LeaveCriticalSection (&csMyCriticalSection);
}
}
}
如果我去掉:
if (dwCommModemStatus & EV_TXEMPTY)
后却可以将数据发出去,但是速度较慢,不知有没有哪位大侠有更好的方法?