- 论坛徽章:
- 0
|
使用32位的api 通信函数:
⑴.在中mainfrm.cpp定义全局变量
handle hcom; // 准备打开的串口的句柄
handle hcommwatchthread ;//辅助线程的全局函数
⑵.打开串口,设置串口
hcom =createfile( "com2", generic_read | generic_write, // 允许读写
0, // 此项必须为0
null, // no security attrs
open_existing, //设置产生方式
file_flag_overlapped, // 我们准备使用异步通信
null );
我使用了file_flag_overlapped结构。这正是使用api实现非阻塞通信的关键所在。
assert(hcom!=invalid_handle_value); //检测打开串口操作是否成功
setcommmask(hcom, ev_rxchar|ev_txempty );//设置事件驱动的类型
setupcomm( hcom, 1024,512) ; //设置输入、输出缓冲区的大小
purgecomm( hcom, purge_txabort | purge_rxabort | purge_txclear
| purge_rxclear ); //清干净输入、输出缓冲区
commtimeouts commtimeouts ; //定义超时结构,并填写该结构
…………
setcommtimeouts( hcom, &commtimeouts ) ;//设置读写操作所允许的超时
dcb dcb ; // 定义数据控制块结构
getcommstate(hcom, &dcb ) ; //读串口原来的参数设置
dcb.baudrate =9600; dcb.bytesize =8; dcb.parity = noparity;
dcb.stopbits = onestopbit ;dcb.fbinary = true ;dcb.fparity = false;
setcommstate(hcom, &dcb ) ; //串口参数配置
上述的commtimeouts结构和dcb都很重要,实际工作中需要仔细选择参数。
⑶启动一个辅助线程,用于串口事件的处理。
windows提供了两种线程,辅助线程和用户界面线程。辅助线程没有窗口,所以它没有自己的消息循环。但是辅助线程很容易编程,通常也很有用。
在次,我们使用辅助线程。主要用它来监视串口状态,看有无数据到达、通信有无错误;而主线程则可专心进行数据处理、提供友好的用户界面等重要的工作。
hcommwatchthread=
createthread( (lpsecurity_attributes) null, //安全属性
0,//初始化线程栈的大小,缺省为与主线程大小相同
(lpthread_start_routine)commwatchproc, //线程的全局函数
getsafehwnd(), //此处传入了主框架的句柄
0, &dwthreadid );
&
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/32596/showart_345849.html |
|