在同步串口编程时,小弟调试了好久,可以WriteFile发送数据到输出缓冲区,但调试到ReadFile接收时,程序运行完,输入缓冲区接收不到数据,不知道怎么回事,求解!!!!!!!
各位同志们,帮小弟看看是不是源码有问题?
...
//打开串口
m_hComm=CreateFile(_T("COM4"), //串口COM4
GENERIC_READ|GENERIC_WRITE, //可读写
0, //独占方式
NULL,
OPEN_EXISTING, //打开一个已经存在的而不是创建
0, //同步方式
NULL);
if(m_hComm==INVALID_HANDLE_VALUE)
{
::AfxMessageBox(_T("打开COM4串口失败!"));
return FALSE;
}
//配置串口
//设置串口的输入、输出缓冲区,以及读写超时
SetupComm(m_hComm,100,100); //输入缓冲区和输出缓冲区都是100
COMMTIMEOUTS timeOuts;
//设定读超时
timeOuts.ReadIntervalTimeout=100;
timeOuts.ReadTotalTimeoutMultiplier=0;
timeOuts.ReadTotalTimeoutConstant=100; //读取一次操作后就立即返回,而不管读取的是否是要求的字符
timeOuts.WriteTotalTimeoutMultiplier=500;
timeOuts.WriteTotalTimeoutConstant=100;
SetCommTimeouts(m_hComm,&timeOuts);
DCB dcb;
GetCommState(m_hComm,&dcb);
dcb.BaudRate=9600; //波特率为9600;
dcb.ByteSize=8; //一个字节为8位
dcb.Parity=NOPARITY; //无奇偶检验位
dcb.StopBits=ONESTOPBIT; //一个停止位
SetCommState(m_hComm,&dcb);
PurgeComm(m_hComm,PURGE_RXCLEAR|PURGE_TXCLEAR);
//发送按钮
void CSynchCommDemoDlg::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
CString strWrite;
this->GetDlgItemTextW(IDC_EDIT_SEND,strWrite);
DWORD error;
COMSTAT csComState;
ClearCommError(m_hComm,&error,&csComState); //恢复到正确状态继续读写
BOOL bWriteState;
DWORD size=strWrite.GetLength();
bWriteState=WriteFile(m_hComm,strWrite,size,&size,NULL);
if(!bWriteState)
{
AfxMessageBox(_T("写串口COM4失败!"));
}
}
//接收按钮
void CSynchCommDemoDlg::OnBnClickedButton2()
{
// TODO: Add your control notification handler code here
DWORD error;
COMSTAT csComState;
ClearCommError(m_hComm,&error,&csComState);
char str[100];
memset(str,0,100);
DWORD wCount=min(100,csComState.cbInQue);//读取的字节数
BOOL bReadStat;
bReadStat=ReadFile(m_hComm,str,wCount,&wCount,NULL);
if(!bReadStat)
AfxMessageBox(_T("读串口COM4失败!"));
PurgeComm(m_hComm, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
this->SetDlgItemTextW(IDC_EDIT_RECEIVE,(LPCTSTR)str);
//CreateThread(NULL,0,Receive,this,0,NULL);
}
//销毁串口
void CSynchCommDemoDlg::OnDestroy()
{
// TODO: Add your message handler code here
CloseHandle(m_hComm);
CDialog::OnDestroy();
}
------解决方案--------------------------------------------------------
你的
wCount=min(100,csComState.cbInQue);
返回值是多少?