Convert serial.read() into a useable string using Arduino?

后端 未结 15 1128
盖世英雄少女心
盖世英雄少女心 2020-11-29 15:27

I\'m using two Arduinos to sent plain text strings to each other using newsoftserial and an RF transceiver.

Each string is perhaps 20-30 characters in length. How do

15条回答
  •  臣服心动
    2020-11-29 16:27

    Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.

    String string = "";
    char ch; // Where to store the character read
    
    void setup() {
        Serial.begin(9600);
        Serial.write("Power On");
    }
    
    boolean Comp(String par) {
        while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
        {
            ch = Serial.read(); // Read a character
            string += ch; // Add it
        }
    
        if (par == string) {
            string = "";
            return(true);
        }
        else {
            //dont reset string
            return(false);
        }
    }
    
    void loop()
    {
        if (Comp("m1 on")) {
            Serial.write("Motor 1 -> Online\n");
        }
        if (Comp("m1 off")) {
            Serial.write("Motor 1 -> Offline\n");
        }
    }
    

提交回复
热议问题