To Windows a serial port or a disk based file both are IO devices . So, in order toopen an existing file ( serial port ) all we need to know the name of the device( COM1) and pass the creation flags as
.If a COM port is opened successfully, the API returns handle to the com port just likea handle to a file. However, if the system could not open the COM port, it wouldreturn
. And you can get the reason by calling
. One of the common errors while opening a COM port is that the COMport is already opened by some other application and in that case you would get
(5). Similarly if you by mistake opened a COM port thatdoesn't exist , you would get
as the last error.Note: Remember not to do make any function calls (like
) before calling
or you would get 0. Once you have opened the com port all you needto do now is to start using it.
Reading and Writing
Now, once you have a com port open, you may want to send some data to theconnected device. For example, lets say you want to send "Hello" to the device(e.g.,another PC). When you want to send the data across the serial port, you need towrite to the serial port just like you would write to a file. You would use followingAPI:
iRet = WriteFile (m_hCommPort,data,dwSize,&dwBytesWritten ,&ov);
where data contains "Hello" . Lets say in response to your "Hello" , the device sendsyou "Hi" . So you need to read the data. Again ,you would use following API:
abRet = ::ReadFile(m_hCommPort,szTmp ,sizeof(szTmp ),&dwBytesRead,&ovRead) ;
For now do not try to understand everything. We will get to all this later. All thissounds very simple. Right?Now lets start digging into issues.
Issues with serial communication
Just now I said, in response to your "Hello", the device may send you "Hi" back andyou would like to read that. But the problem here is that you don't know when thedevice is going to respond? Or will it ever respond? When should you start to readfrom the port. One option is that as soon as you made call to WriteFile, you makecall to ReadFile . If no data is there you need to make read again later on. This leadsto what is called polling. You keep polling the port for data. This model does notreally seem to be a good one. It would be nice if somehow you were notified by thesystem when data has arrived and only then would you make call to ReadFile. This isevent driven approach and fits well into Windows programming. And good news isthat such a model is possible .