基本串行端口通信Visual Studio C ++(浏览现有示例时遇到问题)

时间:2015-03-13 20:52:29

标签: c++ visual-studio-2013 serial-port

我刚刚开始使用C ++,而我无法通过串口找出如何将信息发送到我的arduino(更容易编码)。该信息是使用opencv从我的网络摄像头读取的RGB值。这是我到目前为止(有人帮助我):

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/video/video.hpp>

int main()
{
int delay = 30; // 30 ms between frames
int x = 20; // X coordinate of desired pixel
int y = 140; // Y coordinate of desired pixel
int key = 0;
cv::VideoCapture camera(0);
cv::Mat img;
while(key != 27)
{
camera >> img;
cv::imshow("Web cam image", img);
cv::Vec3b pixel = img.at<cv::Vec3b>(y,x);

// Write the values of pixel to the serial port here 

key = cv::waitKey(delay);
}
return 0;
}

我在网上找到的所有东西看起来都很复杂,而且我一直试图弄清楚几个小时。有没有办法做到这一点并不太复杂?

1 个答案:

答案 0 :(得分:0)

Windows上的串行I / O可能非常复杂,但从根本上说它不需要 - 只需打开端口,设置波特率等,然后写入数据。尝试这样的事情(显然根据需要调整COM端口和参数):

HANDLE hFile = CreateFile("\\\\.\\COM1", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
    DCB port{0};
    port.DCBlength = sizeof(port);
    if (GetCommState(hFile, &port)
    &&  BuildCommDCB("baud=19200 parity=N data=8 stop=1", &port)
    &&  SetCommState(hFile, &port))
    {
        DWORD written;
        // write the data - I'm assuming &pixel[0] will work for a cv vector
        // if not, you'll have to fix this bit yourself
        WriteFile(hFile, &pixel[0], 3, &written, NULL);
    }
    CloseHandle(hFile);
}