【问题标题】:Arduino and Visual C++ Serial CommunicationArduino 和 Visual C++ 串行通信
【发布时间】:2014-12-05 07:40:10
【问题描述】:

所以我找到了这个 Arduino Visual Studio 通信教程: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 以便它只发送一个字符;但是,这会导致输出显示不同步。感谢任何帮助。

【问题讨论】:

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


    【解决方案1】:

    首先,您总是发送nchar 字节,无论您从用户那里读到多少(或很少)。还有你从串口读取的数据,你不会像字符串一样终止它。

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

    然后在接收时,你需要找出你接收了多少字节,然后像字符串一样终止数组(或者在那里也使用std::string,有一个constructor可以让你传入一个指针和一个大小)。

    【讨论】:

    • 谢谢,我明白你的意思了,虽然我还需要添加一个持续读取直到数据可用的 while 循环,但它有所帮助。至少对于第一次读取调用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多