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

问题描述 投票:0回答:2

我正在使用我在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的新输入形式?

非常感谢您阅读此问题。

arduino arduino-c++
2个回答
0
投票

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


-1
投票

[Jdikoklllllsisnsubsygtgaknsubsisbubxincukwokndi

© www.soinside.com 2019 - 2024. All rights reserved.