Welcome to: SysTutorials

Win32下COM口通信控制

这段时间做兼职帮做了一个COM口单片机监控控制程序, 学习了些Win32下COM口的控制.
下面是与COM口控制有关的部分示例代码.

//打开COM1
hCOM=CreateFile(
"COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if (hCOM==INVALID_HANDLE_VALUE) {
MessageBox(
GetForegroundWindow(),"无法打开串口!","操作失败",MB_ICONINFORMATION);
return;
}

 

//设置DCB
DCB dcb;
if (!GetCommState(hCOM,&dcb)) {
MessageBox(
GetForegroundWindow(),"无法获取串口状态!","操作失败",MB_ICONINFORMATION);
hCOM=INVALID_HANDLE_VALUE;
return;
}

dcb.BaudRate=9600;
dcb.ByteSize=8;
dcb.Parity=NOPARITY;
dcb.StopBits=ONESTOPBIT;
if (!SetCommState(hCOM,&dcb)) {
MessageBox(
GetForegroundWindow(),"无法设置串口状态!","操作失败",MB_ICONINFORMATION);
hCOM=INVALID_HANDLE_VALUE;
return;
}

//设置COMMTIMEOUTS
COMMTIMEOUTS communication_timeout;
communication_timeout.ReadIntervalTimeout=MAXDWORD;
communication_timeout.ReadTotalTimeoutMultiplier=0;
communication_timeout.ReadTotalTimeoutConstant=0;
communication_timeout.WriteTotalTimeoutMultiplier=0;
communication_timeout.WriteTotalTimeoutConstant=0;
if (!SetCommTimeouts(hCOM,&communication_timeout)) {
MessageBox(
GetForegroundWindow(),"无法设置串口超时!","操作失败",MB_ICONINFORMATION);
hCOM=INVALID_HANDLE_VALUE;
return;
}

//向串口写入ABC三个字符
ULONG nBytesWritten;
WriteFile(hCOM,"ABC",3,&nBytesWritten,NULL);

//从串口读入三个字符至str
char str[3];
ULONG bytes_read_num;
ReadFile(hCOM,str,3,&bytes_read_num,NULL);

 


本文为此文的备份: https://www.systutorials.com/391/win32下com口通信控制/

posted @ 2010-07-09 23:44  ericzqma  阅读(427)  评论(0编辑  收藏  举报
Welcome to: SysTutorials