How to compare string from Serial.read()?

2019-03-30 06:02发布

问题:

I have this code below where I got from this forum that I followed through. It did not work for me but they claim that the code is fine. I already tried several string comparison methods such as string.equals(string) and the standard == operator, still with no luck.

int ledPin = 13;
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); 
  Serial.println("serial on/off test 0021"); // so I can keep track
}

void loop() {
  while (Serial.available()) {
    delay(3);  
    char c = Serial.read();
    readString += c; 
  }
  if (readString.length() >0) {
    if (readString == "on") {
      Serial.println("switching on");
      digitalWrite(ledPin, HIGH);
    }
    if (readString == "off") {
      digitalWrite(ledPin, LOW);
    }
    readString="";
  } 
}

回答1:

I am able to solve last night problem by simply adding readString.trim(); before string comparison. This is because there will be newline character where id did not print anything in the arduino console.

I place the function as in my code below:

int ledPin = 13;
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT); 
  Serial.println("serial on/off test 0021"); // so I can keep track
}

void loop() {

  while (Serial.available()) {
    delay(3);  
    char c = Serial.read();
    readString += c; 
  }
  readString.trim();
  if (readString.length() >0) {
    if (readString == "on"){
      Serial.println("switching on");
      digitalWrite(ledPin, HIGH);
    }
    if (readString == "off")
    {
      Serial.println("switching off");
      digitalWrite(ledPin, LOW);
    }

    readString="";
  } 
}


回答2:

I just use ' ' (single) instead of " " (double)

char c = Serial.read();

if (c == '1'){ //do something}  


回答3:

Why not use Serial.readString();??

Try this..

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

    void loop(){
      if(Serial.available()){
        String ch;
        ch = Serial.readString();
        ch.trim();
        if(ch=="on"||ch=="ON"){
          digitalWrite(13, HIGH);  
        }
        else if(ch=="off"||ch=="OFF"){
          digitalWrite(13, LOW);
        }
      }
    }


回答4:

I see you try to create some like command line interpreter for test;

You can use Serial command line interpreter for Arduino or just see code, how it's work.

This is not answer, but some help =)



回答5:

solved your code is right you just have to set arduino terminal on "no line ending" you also forgot to write this Serial.println("switching off");

and thanks for sharing your code i am also using your code thanks!!