繁体   English   中英

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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