悬赏园豆:10
[已解决问题]
解决于 2008-06-26 15:55
在提问区里放了老半天没有人答复,只有置于此地,望高人指点......<br>
主要目标:在本机通过com1串口对数据进行读写,不连接任何外接设备,可是怎么也接收不到数据,<br>
发送按钮的代码如下:<br>
m_strPort = "COM1";<br>
hCom=CreateFile(m_strPort,GENERIC_READ|GENERIC_WRITE,<br>
0,NULL,OPEN_EXISTING,<br>
FILE_ATTRIBUTE_NORMAL,//|FILE_FLAG_OVERLAPPED,<br>
NULL);<br>
<br>
if(hCom==INVALID_HANDLE_VALUE) <br>
{ <br>
AfxMessageBox(_T("打开通信端口错误!"), MB_OK, 0);<br>
return false; <br>
}<br>
UpdateData(true); <br>
<br>
<br>
// 对已经打开的串口进行设置<br>
SetupComm(hCom,1024,1024);<br>
// 全部清空发送缓冲区和接收缓冲区<br>
PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);<br>
COMMTIMEOUTS Timeouts;<br>
//DCB dcb;<br>
Timeouts.ReadIntervalTimeout=50;<br>
Timeouts.ReadTotalTimeoutConstant=2000;<br>
Timeouts.ReadTotalTimeoutMultiplier=0;<br>
Timeouts.WriteTotalTimeoutConstant=2000;<br>
Timeouts.WriteTotalTimeoutMultiplier=0;<br>
SetCommTimeouts(hCom,&Timeouts);<br>
m_nSetupbt = 9600;<br>
GetCommState(hCom,&dcb);<br>
dcb.BaudRate=m_nSetupbt;<br>
dcb.ByteSize=8;<br>
dcb.StopBits=ONESTOPBIT;<br>
dcb.Parity=NOPARITY;<br>
dcb.fBinary = TRUE;<br>
dcb.fParity = FALSE;<br>
if(!SetCommState(hCom,&dcb)) <br>
{ <br>
AfxMessageBox(_T("通信端口设置错误!"), MB_OK, 0);<br>
CloseHandle(hCom); <br>
return false; <br>
} <br>
UpdateData(false);<br>
<br>
// 开始传送数据<br>
DWORD length;<br>
//unsigned send[10];<br>
BOOL bWriteStat;<br>
//send[0]=m_sSend;<br>
char send[6]={"china"};<br>
<br>
<br>
<br>
for (int i=0; i<sizeof(send); i++)<br>
{<br>
bWriteStat = WriteFile(hCom,(LPSTR)&send[i],1,&length,m_LpOverlappedWrite);<br>
/*unsigned accept[10] = {0};<br>
bReadStatus = ReadFile(hCom, accept,5,&length,m_OverlappedRead);*/<br>
if( !bWriteStat && ( GetLastError() == ERROR_IO_PENDING ) ){<br>
if( WaitForSingleObject( m_OverlappedWrite.hEvent, 1000 ) ) length = 0;<br>
else{<br>
GetOverlappedResult( hCom, &m_OverlappedWrite, &length, FALSE );<br>
m_OverlappedWrite.Offset += length;<br>
}<br>
}<br>
length++;<br>
}<br>
<br>
return( TRUE );<br>
然后接收是按钮的代码如下:<br>
UpdateData(true);<br>
<br>
DWORD length;<br>
//unsigned accept[10] = {0};<br>
char accept[6];<br>
//char accept[20];<br>
UpdateData(false);<br>
// 接收已经写入串口的数据<br>
<br>
bReadStatus = ReadFile(hCom, &accept,5,&length,m_LpOverlappedRead);<br>
<br>
if (!bReadStatus)<br>
{<br>
if(GetLastError()==ERROR_IO_PENDING)<br>
{<br>
WaitForSingleObject(m_OverlappedRead.hEvent,1000);<br>
return ((int)length);<br>
}<br>
return(0);<br>
}
云淡风清
|
初学一级
|
园豆:
155
提问于:2008-06-25 12:19