處理hCom//全局變量,串口句柄
hcom = create file(" com 1 " ,//com 1端口。
GENERIC_READ|GENERIC_WRITE,//允許讀寫。
0,//獨占模式
空,
OPEN_EXISTING,//打開而不是創建。
0,//同步模式
NULL);
if(hCom==(HANDLE)-1)
{
AfxMessageBox("打開COM失敗!");
返回FALSE
}
返回TRUE
2.配置參數
COMMTIMEOUTS超時;
//設置讀取超時
暫停。ReadIntervalTimeout = 1000;
暫停。ReadTotalTimeoutMultiplier = 500;
暫停。ReadTotalTimeoutConstant = 5000
//設置寫入超時
暫停。WriteTotalTimeoutMultiplier = 500;
暫停。WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom & amp;超時);//設置超時
DCB dcb
GetCommState(hCom & amp;dcb);
dcb。波德拉特= 9600;//波特率是9600。
dcb。ByteSize = 8;//每個字節有8位。
dcb。奇偶性= NOPARITY//沒有奇偶校驗位
dcb。StopBits = TWOSTOPBITS//兩個停止位
SetCommState(hCom & amp;dcb);
3.接收和發送數據
//同步讀取串口
char str[100];
DWORD wCount//讀取的字節數
BOOL bReadStat
bReadStat=ReadFile(hCom,str,100,& ampwCount,NULL);
如果(!面包臺)
{
AfxMessageBox("讀取串口失敗!");
返回FALSE
}
返回TRUE
//同步寫串口
char LPO buffer[100];
DWORD dwbytes write = 100;
COMSTAT ComStat
DWORD dwErrorFlags
BOOL bWriteStat
ClearCommError(hCom & amp;dwErrorFlags。ComStat);
bWriteStat=WriteFile(hCom,lpOutBuffer,dwBytesWrite,& ampdwBytesWrite,NULL);
如果(!bWriteStat)
{
AfxMessageBox("寫串口失敗!");
}
PurgeComm(hCom,PURGE_TXABORT|
PURGE _ rx abort | PURGE _ tx clear | PURGE _ rx clear);