How to compare string from Serial.read()?

后端 未结 6 2328
遇见更好的自我
遇见更好的自我 2021-02-09 11:07

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 compariso

相关标签:
6条回答
  • 2021-02-09 11:12

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

    char c = Serial.read();
    
    if (c == '1'){ //do something}  
    
    0 讨论(0)
  • 2021-02-09 11:14

    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!!

    0 讨论(0)
  • 2021-02-09 11:19

    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 =)

    0 讨论(0)
  • 2021-02-09 11:23

    The new SafeString Arduino Library (available from the Library Manager) make this easy and safe. Unlike Arduino Strings, SafeStrings never causes your sketch to reboot and does not cause heap fragmenation.

    See the detailed tutorial at https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html

    SafeStrings are easy to debug. SafeStrings provide detailed error messages, including the name of SafeString in question, to help you get your program running correctly.

    SafeStrings are safe and robust. SafeStrings never cause reboots and are always in a valid usable state, even if your code passes null pointers or '\0' arguments or exceeds the available capacity of the SafeString.

    SafeString programs run forever. SafeStrings completely avoid memory fragmentation which will eventually cause your program to fail and never makes extra copies when passed as arguments.

    SafeStrings are faster. SafeStrings do not create multiple copies or short lived objects nor do they do unnecessary copying of the data.

    SafeString also has tokenizing/parseing methods. One of the may detailed examples include with the library covers reading user input and parsing for commands WHILE keeping the rest of the sketch running at maximum speed. No evil delay()'s in SafeString methods to stop your sketch in it tracks.

    Note: In the sample code below the size of the SafeStrings is small BUT the code can handle arbitrary long inputs from the user.

    User Serial inputs like
    This is a long input on and off etc
    are handled and parsed just fine.

    SafeString also has extensive debugging and error messages to help you find and fix your coding problems.

    #include "SafeString.h"
    
    const size_t maxCmdLength = 3; // make SafeStrings at least large enough to hold longest cmd
    // Use SafeStrings for the commands as comparing two SafeStrings is generally faster as the lengths can be compared first.
    createSafeString(onCmdStr, maxCmdLength, "on");
    createSafeString(offCmdStr, maxCmdLength, "off");
    
    // input must be large enough to hold longest cmd + 1 delimiter
    createSafeString(input, maxCmdLength + 1); //  to read input cmd + 1 delimiter
    createSafeString(token, maxCmdLength + 1); // for parsing capacity >= input.capacity()
    
    char delimiters[] = " .,\r\n"; // space dot comma CR NL are cmd delimiters
    
    void setup() {
      Serial.begin(9600);    // Open serial communications and wait a few seconds
      SafeString::setOutput(Serial); // enable error messages and debug() output to be sent to Serial
    }
    
    void loop() {
      input.read(Serial); // read from Serial, returns true if at least one character was added to SafeString input
    
      if (input.nextToken(token, delimiters)) { // process at most one token per loop does not return tokens longer than input.capacity()
        if (token == onCmdStr) {
          Serial.println("switching on");
          digitalWrite(ledPin, HIGH)
        } else if (token == offCmdStr) {
          Serial.println("switching off");
          digitalWrite(ledPin, LOW);
        }// else  // not a valid cmd ignore
      }
    }
    
    0 讨论(0)
  • 2021-02-09 11:27

    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);
            }
          }
        }
    
    0 讨论(0)
  • 2021-02-09 11:33

    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="";
      } 
    }
    
    0 讨论(0)
提交回复
热议问题