Serial communication with Arduino with openCV

Hi I am doing a project about openCV and Arduino

Basically a computer with webcam capture something and send some information to Arduino board

I am using Xcode on MacOS and using C++ and openCV 2.4.13

I can achieve serial communication alone with the method below:

But when I implement it with openCV, the [waitKey()] function make it not working:

FILE *arduino = fopen("/dev/xxxxx","w");
int command;

while(cv::waitKey(1) != 'q')
{
//Do sth with openCV
//...

//send 123 to arduino
command = 123;
fprintf(arduino,"%d",command);
fprintf(arduino,"%c",',');
}

fclose(arduino);

When I change the the while loop to while(1), it works, but when I add waitKey (which is necessary in video capturing), it doesn't.

So is there any other way to communicate with Arduino?

Or not using waitKey and keep openCV functioning?

Thanks.

I am not familiar with openCV but I wonder if your while(cv::waitKey(1) != 'q') is terminating and allowing the serial port to close.

Closing and opening the serial port usually causes the Arduino to reset. You should organize your PC program so it opens the serial port and keeps it open until it is completely finished with the Arduino.

Maybe you could use while(1) and inside that loop have an IF to test for the waitKey

...R
Serial Input Basics