arduino c ++多时间通信出现乱码

时间:2019-02-03 11:47:15

标签: arduino arduino-c++

我正在使用在上找到的图书馆 https://github.com/manashmndl/SerialPort 我试图用我的电脑向我的Arduino打个招呼, 然后得到我从Arduino发送的相同字符串。 这是我的C ++代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "SerialPort.h"

using namespace std;

//String for getting the output from Arduino
char output[MAX_DATA_LENGTH];

/*Portname must contain these backslashes, and remember to
replace the following com port*/
const char *port_name = "\\\\.\\COM4";

//String for incoming data
char incomingData[MAX_DATA_LENGTH];

int main()
{
    SerialPort arduino(port_name);

    if (arduino.isConnected())
        cout << "Connection Established" << endl;
    else
        cout << "ERROR, check port name";

    while (arduino.isConnected()) {
        Sleep(1000);

        cout << "Write something: \n";
        std::string input_string = "Hello";
        //Getting input
        //getline(cin, input_string);
        cout << input_string << endl;
        //Creating a c string
        char *c_string = new char[input_string.size() + 1];
        //copying the std::string to c string
        std::copy(input_string.begin(), input_string.end(), c_string);
        //Adding the delimiter
        c_string[input_string.size()] = '\n';
        //Writing string to arduino
        arduino.writeSerialPort(c_string, MAX_DATA_LENGTH);
        //Getting reply from arduino
        arduino.readSerialPort(output, MAX_DATA_LENGTH);
        //printing the output
        puts(output);
        //freeing c_string memory
        delete[] c_string;
    }
}

和Arduino代码

#include <Servo.h>

#define BAUD 9600
//led
#define led 13
//macro for on/off
#define on (digitalWrite(led, HIGH))
#define off (digitalWrite(led, LOW))

void setup() {

  Serial.begin(BAUD);
  pinMode(led, OUTPUT);
}

void loop() {
  String input;

  //If any input is detected in arduino
  if (Serial.available() > 0) {
    on;
    //read the whole string until '\n' delimiter is read
    input = Serial.readStringUntil('\n');
    //while (Serial.available() > 0)
    //  Serial.read();

    Serial.println(input);
    Serial.flush();

    off;
  }
}

我想得到

Connection Established


Write something:
Hello
Hello

Write something:
Hello
Hello

Write something:
Hello
Hello

Write something:
Hello
Hello

Write something:
Hello
Hello

Write something:
Hello
Hello

但我实际上得到了

Connection Established


Write something:
Hello
Hello

Write something:
Hello
楥楥楥q|M爺


Write something:
Hello
?


Write something:
Hello
楥楥楥C|爺


Write something:
Hello 
楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥楥|C爺


Write something:
Hello
楥楥楥q|M爺

自从第一个输出以来出现了一些问题。

我错过了某些事情还是应该做一些事情,然后再阅读Arduino的新输入形式?

非常感谢您阅读此问题。

1 个答案:

答案 0 :(得分:0)

您向Arduino发送的不仅仅是“ hello”,因为您发送的MAX_DATA_LENGTH个字符大多是未定义的。 (至少是“ hello \ n”的前六个字符之后的字符)