所以我找到了Arduino Visual Studio Communication的本教程:http://playground.arduino.cc/Interfacing/CPPWindows

阅读完之后,我在Arduino上编写了一个小程序,该程序读取字符的ASCII代码并返回该递增值。我已经使用串行监视器对其进行了测试。但是,当我在下面编写程序时,不仅会得到答案,而且还会收到“垃圾”。

#include <iostream>
#include <string>
#include "Serial.h"

using namespace std;

int main(int argc, char* argv[])
{
    Serial * Arduino = new Serial("COM8");
    cout << "Communicating with COM7 enter data to be sent\n";
    char data[256] = "";
    int nchar = 256;
    char incomingData[256] = "";
    while (Arduino->IsConnected())
    {
        cin >> data;
        Arduino->WriteData(data, nchar);
        Arduino->ReadData(incomingData, nchar);
        cout << incomingData << endl;
    }
    return 0;
}


输出看起来如下:

F:\Serial\Debug>Serial.exe
Communicating with COM7 enter data to be sent
1
2☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
a
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺b☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺╠╠╠╠╠╠╠╠
^C
F:\Serial\Debug>


任何人都可以阐明我应该如何更改此代码,以便我可以发送和接收特定数量的字符,在这种情况下为一个字符。我已经尝试过将nchar更改为1,以便只发送一个字符。但是,这会导致输出显示不同步。任何帮助表示赞赏,谢谢。

最佳答案

首先,无论您从用户那里读取了多少(或更少),都始终发送nchar字节。而且,您从串行端口读取的数据也不会像字符串一样终止。

首先,很简单,停止使用数组,然后使用std::string(以避免可能的缓冲区溢出),然后发送size字节。

然后在接收时,您需要找出接收到的字节数,然后像字符串一样终止数组(或者也可以在其中使用std::string,有一个constructor可以让您传递指针和大小)。

08-04 10:41