简体   繁体   English

使用 C++ 手柄发送/接收串口 (COM) 数据

[英]Sending/Receiving serial port (COM) data with C++ Handle

I need some help with understanding how to use ReadFile and WriteFile in C++ while using method shown in this guide:在使用本指南中显示的方法时,我需要一些帮助来了解如何在 C++ 中使用 ReadFile 和 WriteFile:

https://www.delftstack.com/howto/cpp/cpp-serial-communication/ https://www.delftstack.com/howto/cpp/cpp-serial-communication/

My question is, how to use these two functions to send or receive anything?我的问题是,如何使用这两个函数来发送或接收任何东西? I don't know how to call them properly我不知道如何正确称呼他们

I start with Handle:我从句柄开始:

// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile(L"COM3", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

Next I did some basic settings like setting baud, bytesize etc. I will skip that.接下来我做了一些基本设置,比如设置波特率、字节大小等。我将跳过它。 And here we come to my problem.在这里,我们来解决我的问题。 I tried to send some data and receive it (my cable output and input pins are connected).我尝试发送一些数据并接收它(我的电缆 output 和输入引脚已连接)。 Problem is I don't know how to call ReadFile and WriteFile properly.问题是我不知道如何正确调用 ReadFile 和 WriteFile。 Here's how I tried to do it:这是我尝试这样做的方法:

    char sBuff[n + 1] = { 0 };
    DWORD send = 0;
    cout << "Sent: " << WriteFile(serialHandle, sBuff, n, &send, NULL) << endl;

    DWORD dwRead = 0;
    cout << "Received: " << ReadFile(serialHandle, sBuff, n, &dwRead, NULL) << endl;

    CloseHandle(serialHandle);
}
}

It's just some attempt to guess the correct method.这只是猜测正确方法的一些尝试。 Any example with short explanation will be much appreciated.任何带有简短解释的示例将不胜感激。

Edit: removed useless chunk of code, hope my question is more understandable now编辑:删除了无用的代码块,希望我的问题现在更容易理解

It's all about the handle "serialHandle" being set to the com3 port instead of the file.这完全是关于将句柄“serialHandle”设置为 com3 端口而不是文件。 The first question, in the layer where you write code, you should not worry about the synchronization or interference of sending and receiving.第一个问题,在你写代码的那一层,你不应该担心发送和接收的同步或干扰。 The serial port handler coordinates it.串行端口处理程序协调它。 Second question, your data is sent as a string of characters that are ASCII.第二个问题,您的数据是作为 ASCII 字符串发送的。 You have to write a function called extract(reciedData) in receiving and place your variables in integer or double or string.您必须在接收中编写一个名为 extract(reciedData) 的 function 并将您的变量放在 integer 或双精度或字符串中。 In fact, you need a protocol, for example, NMEA.事实上,您需要一个协议,例如 NMEA。 please search aboat NMEA protocol in google请在 google 中搜索 aboat NMEA 协议

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

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