win32 API串口同步模式代码示范
源文件下载: vs2015打开
文件名:
MFC_Win32API_同步串口.rar
在OnInitDialog()位置初始化串口:
handleFile1 = CreateFile("COM2",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (handleFile1 == INVALID_HANDLE_VALUE)
{
MessageBox("Error in CreateFile");
return false;
}
DCB dcb;
GetCommState(handleFile1,&dcb);
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.fParity = FALSE;
dcb.StopBits = ONESTOPBIT;
BOOL isTrue;
isTrue = SetCommState(handleFile1,&dcb);
if (isTrue == FALSE)
{
MessageBox("串口参数设置失败");
return FALSE;
}
COMMTIMEOUTS timeous;
timeous.ReadIntervalTimeout = 1000;
isTrue = SetCommTimeouts(handleFile1,&timeous);
if (isTrue == FALSE)
{
MessageBox("串口超时设置失败");
return FALSE;
}
//设置缓冲区的大小
SetupComm(handleFile1,1024,1024);
isTrue = PurgeComm(handleFile1,PURGE_RXABORT|PURGE_RXCLEAR|PURGE_TXABORT|PURGE_TXCLEAR);
if (isTrue == FALSE)
{
MessageBox("清除缓冲区炒作失败");
return FALSE;
}
按钮触发事件:
void CMFC_Win32API_同步串口Dlg::OnBnClickedButtonRecv1()
{
// TODO: 在此添加控件通知处理程序代码
char buff[1024];
DWORD dword;
BOOL isTrue = ReadFile(handleFile1,buff,1024,&dword,0);
if (isTrue)
{
MessageBox("读取成功");
}
m_Recv1 = buff;
UpdateData(false);//更新编辑框数据
}
void CMFC_Win32API_同步串口Dlg::OnBnClickedButtonSend1()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
DWORD dwError;
COMSTAT comstat;
ClearCommError(handleFile1,&dwError,&comstat);
DWORD dword;
BOOL isTrue = WriteFile(handleFile1,m_SendText1.GetBuffer(1),m_SendText1.GetLength()+1,&dword,0);
if (isTrue)
{
MessageBox("发送成功");
}
}