深入浅出VC++串口编程之基于Win32 API
2008-10-09 19:26:55 来源:WEB开发网以下程序将串口读操作的超时设定为10 毫秒:
COMMTIMEOUTS to;
与SetCommTimeouts对应的GetCommTimeouts()函数的原型为:
memset(&to, 0, sizeof(to));
to.ReadIntervalTimeout = 10;
SetCommTimeouts(hCom, &to);
BOOL GetCommTimeouts(
HANDLE hFile, // handle of communications device
LPCOMMTIMEOUTS lpCommTimeouts // pointer to comm time-out structure
);
事件设置
在读写串口之前,需要用SetCommMask ()函数设置事件掩模来监视指定通信端口上的事件,其原型为:
BOOL SetCommMask(
有了Set当然还会有Get,与SetCommMask对应的GetCommMask()函数的原型为:
HANDLE hFile, //标识通信端口的句柄
DWORD dwEvtMask //能够使能的通信事件
);
BOOL GetCommMask(
HANDLE hFile, //标识通信端口的句柄
LPDWORD lpEvtMask // address of variable to get event mask
);
串口上可以发生的事件可以是如下事件列表中的一个或任意组合:EV_BREAK、EV_CTS、EV_DSR、EV_ERR、EV_RING、EV_RLSD、EV_RXCHAR、EV_RXFLAG、EV_TXEMPTY。 我们可以用WaitCommEvent()函数来等待串口上我们利用SetCommMask ()函数设置的事件:
BOOL WaitCommEvent(
HANDLE hFile, //标识通信端口的句柄
LPDWORD lpEvtMask, // address of variable for event that occurred
LPOVERLAPPED lpOverlapped, // address of overlapped structure
);
WaitCommEvent()函数一直阻塞,直到串口上发生我们用所SetCommMask ()函数设置的通信事件为止。一般而言,当WaitCommEvent()返回时,程序员可以由分析*lpEvtMask而获得发生事件的类别,再进行相应的处理。
读串口
对串口进行读取所用的函数和对文件进行读取所用的函数相同,读函数原型如下:
BOOL ReadFile(
HANDLE hFile, // handle of file to read
LPVOID lpBuffer, // pointer to buffer that receives data
DWORD nNumberOfBytesToRead, // number of bytes to read
LPDWORD lpNumberOfBytesRead, // pointer to number of bytes read
LPOVERLAPPED lpOverlapped // pointer to structure for overlapped I/O
);
写串口
对串口进行写入所用的函数和对文件进行写入所用的函数相同,写函数原型如下:
BOOL WriteFile(
HANDLE hFile, // handle to file to write to
LPCVOID lpBuffer, // pointer to data to write to file
DWORD nNumberOfBytesToWrite, // number of bytes to write
LPDWORD lpNumberOfBytesWritten, // pointer to number of bytes written
LPOVERLAPPED lpOverlapped // pointer to structure for overlapped I/O
);
关闭串口
利用API 函数实现串口通信时关闭串口非常简单,只需使用CreateFile 函数返回的句柄作为参数调用CloseHandle 即可:
BOOL CloseHandle(
HANDLE hObject // handle to object to close
);
更多精彩
赞助商链接