串口通信主要用到下面几个函数:
CreateFile | 打开通信端口 |
CloseHandle | 关闭通信端口 |
GetCommState | 取得端口的参数 |
SetCommState | 设置端口参数 |
WriteFile | 端口发送数据 |
ReadFile | 端口读取数据 |
ClearCommError | 清除端口错误,并取得信息 |
PurgeComm | 清除数据缓冲区 |
SetCommMask | 设置触发事件 |
WaitCommEvent | 等待事件触发 |
EscapeCommFunction | 控制端口的硬件状态 |
GetCommModemState | 取得端口硬件线路状态 |
(1)串口同步通信
Handle hComm=CreateFile("COM1",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,0); //打开COM1端口
if(hComm==INVALID_HANDLE_VALUE)
//打开端口失败
else
{
DCB dcb;
GetCommState(hComm,&dcb);//取得端口状态
dcb.BaudRate=CBR_9600; //波特率设为9600
dcb.ByteSize=8;//字节为8位
dcb.Parity=NOPARITY;//无校验
dcb.StopBits=ONESTOPBIT;//1位停止位
if(!SetCommState(hComm,&dcb))
{
//端口状态设置失败
CloseHandle(hComm);
}
else
//端口设置成功
}
读数据
char inbuff[1024];
DWORD nBytesRead,dwEvent,dwError;
COMSTAT cs;
//取得状态
ClearCommError(hComm,&dwError,&cs);
if(cs.cbInQue>sizeof(inbuff))//数据是否大于缓冲区
{
PurgeComm(hComm,PURGE_RXCLEAR);
return;
}
ReadFile(hComm,inbuff,cs.cbInQue,&nBytesRead,NULL);
....
发送数据
...
WriteFile(hComm,SendData,sizeof(SendData),&nBytesSend,NULL);
...
(2)串口异步通信
使用同步通信时,读数据时若端口没有数据,程序将一直停在ReadFile处,程序当掉.解决的办法是使用异步通信.
Handle hComm=CreateFile("COM1",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,//使用异步通信方式
0); //打开COM1端口
if(hComm==INVALID_HANDLE_VALUE)
//打开端口失败
else
{
DCB dcb;
GetCommState(hComm,&dcb);//取得端口状态
dcb.BaudRate=CBR_9600; //波特率设为9600
dcb.ByteSize=8;//字节为8位
dcb.Parity=NOPARITY;//无校验
dcb.StopBits=ONESTOPBIT;//1位停止位
if(!SetCommState(hComm,&dcb))
{
//端口状态设置失败
CloseHandle(hComm);
}
else
//端口设置成功
long EvWait;
EvWait=EV_ERR + EV_BREAK + EV_RXCHAR;
if(!SetCommMask(hComm,EvWait))
//设置失败
}
收数据
TEvent *WEvent;
OVERLAPPED OverLap;
TWaitResult EE;
unsigned long EvWait;
WEvent=new TEvent(NULL,true,false,"");
OverLap.hEvent=WEvent->Handle;
if(WaitCommEvent(hComm,&EvWait,&OverLap))
{
EE!=wrSignaled)return;//未触发
WEvent->ResetEvent();
if(EvWait & EV_RXCHAR)
{
ReadFile(..);
}