Open COM port something like this:
hCom = OpenComPort("COM1");
HANDLE OpenComPort(char *szPort)
{
HWND hWnd;
HANDLE hCom;
DCB dcb;
COMMTIMEOUTS cto;
BOOL bOk;
char szTmp[80];
if (!szPort) return 0;
hWnd = hDlg;
hCom = CreateFile(szPort, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if ( hCom == (HANDLE)-1 ) {
wsprintf(szTmp, "Error opening port %s", szPort);
MessageBox( hWnd, szTmp, szAppName, MB_OK|MB_ICONERROR );
return 0;
}
bOk = GetCommState(hCom, &dcb);
if ( !bOk ) {
CloseHandle(hCom);
wsprintf(szTmp, "Error reading port %s state", szPort);
MessageBox( hWnd, szTmp, szAppName, MB_OK|MB_ICONERROR );
return 0;
}
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;
bOk = SetCommState(hCom, &dcb);
if ( !bOk ) {
CloseHandle(hCom);
wsprintf(szTmp, "Error writing port %s state", szPort);
MessageBox( hWnd, szTmp, szAppName, MB_OK|MB_ICONERROR );
return 0;
}
cto.ReadIntervalTimeout = 100;
cto.ReadTotalTimeoutMultiplier = 10;
cto.ReadTotalTimeoutConstant = 1000;
cto.WriteTotalTimeoutMultiplier = 500;
cto.WriteTotalTimeoutConstant = 1000;
bOk = SetCommTimeouts(hCom, &cto);
return hCom;
}
and use ReadFile and WriteFile functions.
finally close port like this:if (hCom) CloseHandle(hCom);