How to Open an RS232 Com Port in Visual C++

USB com ports are typically assigned port numbers greater than 9, which impacts how the CreateFile function must be called. For COM numbers less than 9 CreateFile is called with a string such as: "COM1". For numbers greater than 9, a prefix of "\\.\" must be added to the com port string, for example "\\.\COM24". Fortunately, the prefix can be added to ports below 9 as well, and so for consistency, just add the prefix to any comport string.Since back slash is a escape special character they must be paired, in the code.

hComPort= CreateFile("\\\\.\\COM24", GENERIC_READ |GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);

if (hComPort == INVALID_HANDLE_VALUE){
hComPort= 0;
return (lastError= ERR_OPEN_COMM); /* Error! */
}

Water Level Sensor


© Copyright 2019 Daycounter, Inc. All rights Reserved. There is no guarantee for any information on this website. Use at your own risk.