简体   繁体   English

使用 Arduino 回显串行字符串

[英]Echo Serial Strings with Arduino

EDIT 2: I got the solution.编辑 2:我得到了解决方案。 Anytime someone wants the code I'd be happy to provide.任何时候有人想要我很乐意提供的代码。 Peace.和平。

Topic: I'm trying an experiment of echoing strings that I receive in my arduino.主题:我正在尝试对我在 arduino 中收到的字符串进行回显实验。 So this is the code so far:所以这是到目前为止的代码:

byte byteRead = 0;
bool readable = LOW;

char fullString[50];
int index = 0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  // State 1
  if (Serial.available()) {
    readable = HIGH; // flag to enter in the next state when there's nothing else to read
    byteRead = Serial.read();
    fullString[index] = (char)byteRead;
    index++;
  }
  // State 2
  if (readable == HIGH && !Serial.available()){
    fullString[index] = '\0'; // '\0' to terminate the string
    Serial.println(fullString);
    // resets variables
    index = 0;
    readable = LOW;
  }
  /** 
   *  Somehow a delay prevents characters of the string from having 
   *  a line printed between them.
   *  Anyways, when the string is too long, a line is printed between 
   *  the first and second characters
   */
   delay(5); 
}

Somehow this delay in the end prevents the characters of the string from having a line printed between them, like this:不知何故,这种延迟最终会阻止字符串的字符在它们之间打印一行,如下所示:

H H

e电子

l

l

o

Nonetheless, when the string is too long, a line is printed between the first and second characters.尽管如此,当字符串太长时,会在第一个和第二个字符之间打印一行。

Do you know a better way of doing this?你知道这样做的更好方法吗?

EDIT: Next time I'd appreciate answers from someone who actually KNOWS programming.编辑:下次我会感谢真正了解编程的人的回答。 Not just condescending idiots.不只是鄙视白痴。

that's my String Echo那是我的字符串回声

#define MAX_BUFFER_SIZE 0xFF
char buffer[MAX_BUFFER_SIZE];

void setup() {
  Serial.begin(115200);
  buffer[0] = '\0';
}

void loop() {
  while (Serial.available() > 0) {
    char incomingByte;
    size_t i = 0;
    do {
      incomingByte = Serial.read();
      buffer[i++] = incomingByte;
    } while (incomingByte != '\0' && i < MAX_BUFFER_SIZE);
    if(i > 0){
      delay(1000);   /// delay for the echo
      Serial.write(buffer, i);
    }
  }  
}

You want to echo the string read, so just echo the input.您想回显读取的字符串,因此只需回显输入即可。

void setup() {
  Serial.begin(9600);
}

void loop() {
  int c = Serial.read();
  if (c >= 0) Serial.write(c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM