COM Port Programming in Win32

Posted on In Programming

The 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);

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *