Reading from two serial ports simultaneously in c++
The op开发者_运维百科erating system I am working with is Windows 7. I am needing to grab data at certain intervals from a broadband card. This car sends data to two separate COM ports. COM 3 and COM 4. Every interval I will need to query the line of info on both serial ports and write them to a file.
How do I read from two COM ports? Do I have to use threading? Is it good practice opening both at the same time?
Take a look at this tutorial. If you open up the com port and then make a call to WaitComEvent in overlapped IO you'll get a handle in the OVERLAPPED that can be used in WaitForMultipleObjects.
You should be able to do it in a single thread with the general outline below:
HANDLE hSerial3;
hSerial3 = CreateFile("COM3",
GENERIC_READ | GENERIC_WRITE,
0,0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
//...
WaitCommEvent(hSerial3, &dwEventMask, &ov3);
WaitCommEvent(hSerial4, &dwEventMask, &ov4);
//pack ov.hEvent into arHandler
WaitForMultipleObjects (3,arHandles,FALSE,INFINITE);
Heavily edited due to feedback from @JimRhodes
You will read from both ports the same way that you read from one port. Since both ports are independent, there is no issue. Have one thread to read from say COM3 and another thread to read from COM4. Yes it is absolutely fine to read from both ports at the same time, nothing wrong with it. In fact you can even read from many more ports at the same time not just two.
you can check this site gives an example http://www.fogma.co.uk/foggylog/archive/140.html
You need to open each port as a file. The names to use would be "COM3:" and "COM4:". You will want to set an event mask (SetCommEvent) and create a thread to read from each port. You use WaitCommEvent in your thread and check if the event is for received data. If so you use ReadFile to read the data.
It sounds like your design is to poll the ports for data queued there. This is the simplest way to read data from these ports. You can use one thread to poll the two ports, one after the other.
Open COM3
Open COM4
LOOP
Check for data on COM3.
If data, read and process
Check for data on COM4.
If data, read and process
Sleep for remainder of polling interval
repeat from LOOP
All this should probably be done in one thread, so that another main thread can look after user interaction, etc, while the polling thread sleeps.
Whether or not to do the data processing in this thread or in another depends ... on a lot of details.
You should always use threading when communicating with COM ports.
Otherwise your program will be yet another of those incredibly crappy amateur ones that lock up the main GUI thread completely while waiting for the COM port. Nothing screams "I'm a bad programmer" more than such programs, in my opinion.
In this particular case, using several threads sounds like a sensible choice.
精彩评论