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 から新しい入力を読み取る前に、何かを見逃していましたか?
この質問を読んでいただきありがとうございます。