Arduino从Serial读取字符串

Dav*_*mes 5 c arduino

#include <stdio.h>

#define LED 13

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int i;
  char command[5];
  for (i = 0; i < 4; i++) {
    command[i] = Serial.read();
  }
  command[4] = '\0';

  Serial.println(command);

  if (strcmp(command, "AAAA") == 0) {
    digitalWrite(LED, HIGH);
    Serial.println("LED13 is ON");
  } else if (strcmp(command, "BBBB") == 0) {
    digitalWrite(LED, LOW);
    Serial.println("LED13 is OFF");
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图用Arduino的Serial读取一个4个字符长的字符串,当它是AAAA时打开一个LED,当它是BBBB时关闭串口.

但是,当我输入"AAAA"时,它会显示"AAAÿ"并且沿途有很多"ÿ".

我认为我正在正确地阅读所有内容,但它运作得不好,对我做错了什么的想法?

小智 9

String txtMsg = "";  
char s;

void loop() {
    while (serial.available() > 0) {
        s=(char)serial.read();
        if (s == '\n') {
            if(txtMsg=="HIGH") {  digitalWrite(13, HIGH);  }
            if(txtMsg=="LOW")  {  digitalWrite(13, LOW);   }
            // Serial.println(txtMsg); 
            txtMsg = "";  
        } else {  
            txtMsg +=s; 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 1

#define numberOfBytes 4
char command[numberOfBytes];

    void serialRX() {
      while (Serial.available() > numberOfBytes) {
        if (Serial.read() == 0x00) { //send a 0 before your string as a start byte
          for (byte i=0; i<numberOfBytes; i++)
            command[i] = Serial.read();
        }
      }
    }
Run Code Online (Sandbox Code Playgroud)