没用过cserialPort
自己常用这样
创建线程监听吧
贴下代码给你参考
//初始化打开IO端口
void CgameDlg::init_io_com()
{
//打开串口,设置串口
hCom=CreateFile(
TEXT("COM1"),
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
//检测打开串口操作是否成功
//若成功则建立线程监听端口
if(hCom!=INVALID_HANDLE_VALUE)
{
SetupComm( hCom,1024,1024) ; //设置输入、输出缓冲区的大小
COMMTIMEOUTS CommTimeOuts ; //定义超时结构,并填写该结构
CommTimeOuts.ReadIntervalTimeout=MAXDWORD; //把间隔超时设为最大,把总超时设为0将导致ReadFile立即返回并完成操作
CommTimeOuts.ReadTotalTimeoutMultiplier=0; //读时间系数
CommTimeOuts.ReadTotalTimeoutConstant=0; //读时间常量
CommTimeOuts.WriteTotalTimeoutMultiplier=1000;//总超时=时间系数*要求读/写的字符数+时间常量
CommTimeOuts.WriteTotalTimeoutConstant=2000; //设置写超时以指定WriteComm成员函数中的
SetCommTimeouts( hCom, &CommTimeOuts ) ;//设置读写操作所允许的超时
DCB dcb ; // 定义数据控制块结构
GetCommState(hCom, &dcb ) ; //读串口原来的参数设置
dcb.BaudRate =115200;
dcb.ByteSize =8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT ;
dcb.fBinary = TRUE ;
dcb.fParity = FALSE;
SetCommState(hCom, &dcb ) ; //串口参数配置
PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR| PURGE_RXCLEAR ); //清干净输入、输出缓冲区
hCommWatchThread=CreateThread(
NULL, //安全属性
0, //初始化线程栈的大小,缺省为与主线程大小相同
CommWatchProc, //线程的全局函数
AfxGetMainWnd()->m_hWnd, //此处传入了主框架的句柄
0,
NULL
);
}
//若不成功则提示用户打开端口出错
else
{
AfxMessageBox(L"IO板连接串口被占用或不存在");
}
}
//监听函数
//初始化IO板子的监听
DWORD WINAPI CommWatchProc(LPVOID lpParameter)
{
//定义存储监听到的数据的数组
DWORD dwEvtMask=0;
while(true)
{
SetCommMask(hCom, EV_RXCHAR|EV_TXEMPTY );//有哪些串口事件需要监视?
WaitCommEvent(hCom, &dwEvtMask,0); // 等待串口通信事件的发
Sleep(20);
memset(&lpInBuffer,'\0',sizeof(lpInBuffer));
cBytes=ReadPort(hCom,lpInBuffer);
if(cBytes>0)
{
::PostMessage((HWND)lpParameter,WM_RECVDATA1,0,0);
}
}
return 0;
}
//读取端口的函数
int ReadPort(HANDLE hCom,char buffer[1000])
{
DWORD dwBytesRead=1000;
BOOL bReadStatus;
DWORD dwErrorFlags;
COMSTAT ComStat;
OVERLAPPED m_osRead;
memset(&m_osRead,0,sizeof(OVERLAPPED));
m_osRead.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
ClearCommError(hCom,&dwErrorFlags,&ComStat);
if(!ComStat.cbInQue)
{
return 0;
}
dwBytesRead=min(dwBytesRead,(DWORD)ComStat.cbInQue);
bReadStatus=ReadFile(hCom, buffer,dwBytesRead,
&dwBytesRead,&m_osRead);
if(!bReadStatus) //如果ReadFile函数返回FALSE
{
if(GetLastError()==ERROR_IO_PENDING)
{
GetOverlappedResult(hCom,&m_osRead,&dwBytesRead,TRUE);
// GetOverlappedResult函数的最后一个参数设为TRUE,
//函数会一直等待,直到读操作完成或由于错误而返回。
return dwBytesRead;
}
return 0;
}
return dwBytesRead;
}
//写串口的函数
int WritePort(HANDLE hCom,char buffer[],DWORD len)
{
DWORD dwBytesWritten=len;
OVERLAPPED m_osWrite;
BOOL bWriteStat;
memset(&m_osWrite,0,sizeof(OVERLAPPED));
m_osWrite.hEvent=CreateEvent(NULL,TRUE,FALSE,NULL);
bWriteStat=WriteFile(hCom,buffer,dwBytesWritten,
&dwBytesWritten,&m_osWrite);
if(!bWriteStat)
{
if(GetLastError()==ERROR_IO_PENDING)
{
WaitForSingleObject(m_osWrite.hEvent,1000);
return dwBytesWritten;
}
return 0;
}
return dwBytesWritten;
}
posted on 2012-09-10 14:23
梦的飞翔 阅读(602)
评论(0) 编辑 收藏 引用