简体   繁体   中英

Read from serial port only when data is send from other side (c++)

I am doing serial communication in win32. I have used separate thread to write and read. This is because i have to continuously send the data till the application is running without affecting other part of the program and I have to continuously read the data from the serial port.

The main function (WINAPI WinMain) has

_beginthread(serialFunctionSend,0,(void*)12); // start new thread for send (write)
_beginthread(SerialFunctionReceive,0,(void*)10);//start new thread for receive(read)

the send function is continuously sending the data. My problem is in the receive function. It can receive the data. But I am wandering how to check whether data has been received or not . In other words, how to check our system has received any data. I have to perform some task only when something is received not when we donot receive anything at the port. So i have to exclude the condition when program has not received anything.

My "SerialFunctionReceive" code is

void SerialFunctionReceive(void * arg)
{
char inBuffer[BUF_SIZE];
while (statusRead ==true)
{
DWORD nBytesRead = serialObj.ReadTest(inBuffer, sizeof(inBuffer));
}
}

Can we do this by checking the value of inBuffer as read data is stored in it. How can we check that inBuffer has some value or not. Or is there is other options to check whether read event has taken place .

you can poll the buffer.

DWORD nBytesRead = serialObj.ReadTest(inBuffer, sizeof(inBuffer));
if (nBytesRead == 0)
{
   //no data
}
else
{
   //do something
}

I guess you need to do this in a while loop since you never know when you get new data.

First of all, you have to make sure your serial port is opened as an Overlapped I/O in order to send and to receive at the same time. If you did so, the WaitForSingleObject() is useful for you.

OVERLAPPED ov = {0};
ov.hEvent = CreateEvent(NULL, true, false, NULL);
DWORD dwEvtMask;
WaitCommEvent(hSerialPort, &dwEvtMask, &ov);
WaitForSingleObject(ov.hEvent, INFINITE);

Where hSerialPort is the return value of CreateFile() who opened your serial port. The program will be blocked at the last line before any data comes in. So you don't have to poll it all the time.

See CreateFile for more detail.

And you may be interested in this page .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM