我正在使用我在 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 之前,我是否遗漏了什么或者我应该做些什么?
非常感谢您阅读这个问题。