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

Basic Serial Port Communication Visual Studio C++ (having trouble wading through existing examples)

本文关键字:问题 遇到 浏览 通信 串行端口 Visual Studio C++      更新时间:2023-10-16

我刚刚开始使用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;
}

我在网上找到的所有内容似乎都非常复杂,我已经试图弄清楚几个小时了。 有没有不太复杂的方法

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);
}