COM Port Programming in Win32
Posted on In ProgrammingThe control support for the COM port under Win32 can be used to operate the COM port, such as a monitoring and control program for a single-chip microcontroller.
Below is an example code related to COM port control:
// Open COM1
hCOM=CreateFile(
"COM1",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
if (hCOM==INVALID_HANDLE_VALUE) {
MessageBox(
GetForegroundWindow(),"Can not open the COM port!","Operation Failed",MB_ICONINFORMATION);
return;
}
// Configure DCB
DCB dcb;
if (!GetCommState(hCOM,&dcb)) {
MessageBox(
GetForegroundWindow(),"Can't read the status of the COM port!","Operation Failed",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(),"Can't config the status of the COM port!","Operation Failed",MB_ICONINFORMATION);
hCOM=INVALID_HANDLE_VALUE;
return;
}
// Set 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(),"Timed out to set COM port!","Operation Failed",MB_ICONINFORMATION);
hCOM=INVALID_HANDLE_VALUE;
return;
}
// Write ABC to the COM port
ULONG nBytesWritten;
WriteFile(hCOM,"ABC",3,&nBytesWritten,NULL);
// Read 3 byte and put it in the str buffer
char str[3];
ULONG bytes_read_num;
ReadFile(hCOM,str,3,&bytes_read_num,NULL);