Edu串行字符串与Arduino

时间:2015-11-17 20:23:39

标签: string arduino

编辑2:我得到了解决方案。任何时候有人想要我愿意提供的代码。和平。

主题: 我正在尝试回应我在arduino中收到的字符串的实验。 所以这是到目前为止的代码:

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); 
}

不知何故,这种延迟最终会阻止字符串的字符在它们之间打印一条线,如下所示:

ħ

ë

1

1

0

尽管如此,当字符串太长时,会在第一个和第二个字符之间打印一行。

你知道更好的方法吗?

编辑:下次我会欣赏那些真正懂得编程的人的答案。不只是居高临下的白痴。

2 个答案:

答案 0 :(得分:0)

你想要回显字符串读取,所以只需回显输入。

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

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

答案 1 :(得分:0)

那是我的字符串回声

#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);
    }
  }  
}