How to compare a stringHow to split in stringHow to get string parts from string?How to writte simple string compare?I2C_Anything String / Char Array issuesHow to clear of contents of string in Arduino?How to convert String to Double?WebSocket client for ArduinoHttpClient conditional if with readString() incoming data bufferSending a string to arduino and is not reacting to itHow to compare two string?String compare when using Serial

Label inside tikzcd square

What do you call someone who asks many questions?

Mathematica command that allows it to read my intentions

Machine learning testing data

how do we prove that a sum of two periods is still a period?

Why were 5.25" floppy drives cheaper than 8"?

Implication of namely

How seriously should I take size and weight limits of hand luggage?

What's the meaning of "Sollensaussagen"?

What is the opposite of "eschatology"?

OP Amp not amplifying audio signal

Forgetting the musical notes while performing in concert

Am I breaking OOP practice with this architecture?

Is it a bad idea to plug the other end of ESD strap to wall ground?

Getting extremely large arrows with tikzcd

Different meanings of こわい

Processor speed limited at 0.4 Ghz

Why was the shrink from 8″ made only to 5.25″ and not smaller (4″ or less)

Finding the reason behind the value of the integral.

Was the Stack Exchange "Happy April Fools" page fitting with the '90's code?

How to show a landlord what we have in savings?

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

In the UK, is it possible to get a referendum by a court decision?

Why was Sir Cadogan fired?



How to compare a string


How to split in stringHow to get string parts from string?How to writte simple string compare?I2C_Anything String / Char Array issuesHow to clear of contents of string in Arduino?How to convert String to Double?WebSocket client for ArduinoHttpClient conditional if with readString() incoming data bufferSending a string to arduino and is not reacting to itHow to compare two string?String compare when using Serial













1















How to compare a string coming from serial monitor with some predefined text stored as a local variable?
if i say:



int led = 2;
String a = " abcds";
void setup()
Serial.begin(9600);


void loop(){
String b = Serial.read();
Serial.println(b);

if(b != a)
digitalWrite(2,LOW);

else

digitalWrite(2,HIGH);



just as an example, this code will not compile because on the serial i receive bytes and i want to compare with a string.
So my question is...
how should be done?



Thanks in advance !










share|improve this question







New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

    – Jot
    6 hours ago















1















How to compare a string coming from serial monitor with some predefined text stored as a local variable?
if i say:



int led = 2;
String a = " abcds";
void setup()
Serial.begin(9600);


void loop(){
String b = Serial.read();
Serial.println(b);

if(b != a)
digitalWrite(2,LOW);

else

digitalWrite(2,HIGH);



just as an example, this code will not compile because on the serial i receive bytes and i want to compare with a string.
So my question is...
how should be done?



Thanks in advance !










share|improve this question







New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

    – Jot
    6 hours ago













1












1








1








How to compare a string coming from serial monitor with some predefined text stored as a local variable?
if i say:



int led = 2;
String a = " abcds";
void setup()
Serial.begin(9600);


void loop(){
String b = Serial.read();
Serial.println(b);

if(b != a)
digitalWrite(2,LOW);

else

digitalWrite(2,HIGH);



just as an example, this code will not compile because on the serial i receive bytes and i want to compare with a string.
So my question is...
how should be done?



Thanks in advance !










share|improve this question







New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












How to compare a string coming from serial monitor with some predefined text stored as a local variable?
if i say:



int led = 2;
String a = " abcds";
void setup()
Serial.begin(9600);


void loop(){
String b = Serial.read();
Serial.println(b);

if(b != a)
digitalWrite(2,LOW);

else

digitalWrite(2,HIGH);



just as an example, this code will not compile because on the serial i receive bytes and i want to compare with a string.
So my question is...
how should be done?



Thanks in advance !







string






share|improve this question







New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 7 hours ago









Iulian ChirvasaIulian Chirvasa

82




82




New contributor




Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Iulian Chirvasa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

    – Jot
    6 hours ago

















  • For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

    – Jot
    6 hours ago
















For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

– Jot
6 hours ago





For which arduino board? Most of us try to avoid the String class for the arduino uno. As soon as a character is available, you add it to a buffer or to a String. Sometimes the data from the serial port is closed with a linefeed, then you can process the text in the buffer or in the String when a linefeed is read.

– Jot
6 hours ago










4 Answers
4






active

oldest

votes


















1














If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/



It has a function compareTo() that should do what you need.






share|improve this answer






























    1














    C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.






    share|improve this answer








    New contributor




    Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




















    • I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

      – Duncan C
      5 hours ago


















    1














    version using String (not recommended)



    #define LED 2
    const char* a = "abcd";

    void setup()
    Serial.begin(115200);
    pinMode(LED, OUTPUT);


    void loop()
    if (Serial.available())
    String s = Serial.readStringUntil('n');
    s.trim();
    if (s == a)
    digitalWrite(LED, HIGH);
    else
    digitalWrite(LED, LOW);





    the version with C-string:



    #define LED 2
    const char* a = "abcd";
    char buffer[32];

    void setup()
    Serial.begin(115200);
    pinMode(LED, OUTPUT);


    void loop()
    if (Serial.available())
    size_t l = Serial.readBytesUntil('n', buffer, sizeof(buffer - 1));
    if (buffer[l - 1] == 'r')
    l--;

    buffer[l] = 0; // the terminating zero
    Serial.println(buffer);
    if (strcmp(buffer, a) == 0)
    digitalWrite(LED, HIGH);
    else
    digitalWrite(LED, LOW);








    share|improve this answer























    • As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

      – Edgar Bonet
      4 hours ago











    • The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

      – VE7JRO
      3 hours ago


















    0














    Here is a test sketch that uses a char array VS the String object. Please remember to set the serial monitor to send a newline only.



    char inputBuffer[16];
    char compareToThisString[] = "test string";

    void setup()
    Serial.begin(9600);


    void loop()

    if(Serial.available() > 0)

    Serial.readBytesUntil('n', inputBuffer, 16);

    if(strcmp(compareToThisString, inputBuffer) == 0)
    Serial.println("Matches");

    else
    Serial.println("No Match");


    memset(inputBuffer, 0, sizeof(inputBuffer));



    As Egar Bonet mentions in his comments, there is a (up to) one second delay before Serial.readBytesUntil() terminates. That does not apply to the sketch I've written because the function terminates as soon as it receives the n character. Serial.readBytesUntil() is blocking code, but that is a different matter which may or may not be an issue for you, depending on what you're building and how much data you are sending. To reduce the timeout period, there is a Serial.setTimeout() function which could be set to whatever you want, but it only comes into play if you don't send the n character.






    share|improve this answer

























    • why the memset?

      – Juraj
      4 hours ago






    • 1





      read max 15 to have one zero left in the array

      – Juraj
      4 hours ago











    • I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

      – VE7JRO
      4 hours ago











    • Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

      – Edgar Bonet
      4 hours ago











    • "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

      – VE7JRO
      4 hours ago











    Your Answer






    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("schematics", function ()
    StackExchange.schematics.init();
    );
    , "cicuitlab");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "540"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Iulian Chirvasa is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2farduino.stackexchange.com%2fquestions%2f63106%2fhow-to-compare-a-string%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    4 Answers
    4






    active

    oldest

    votes








    4 Answers
    4






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/



    It has a function compareTo() that should do what you need.






    share|improve this answer



























      1














      If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/



      It has a function compareTo() that should do what you need.






      share|improve this answer

























        1












        1








        1







        If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/



        It has a function compareTo() that should do what you need.






        share|improve this answer













        If you do a Google search on "Arduino String" you should find a class reference on the String class. https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/



        It has a function compareTo() that should do what you need.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 7 hours ago









        Duncan CDuncan C

        1,9701618




        1,9701618





















            1














            C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.






            share|improve this answer








            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.




















            • I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

              – Duncan C
              5 hours ago















            1














            C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.






            share|improve this answer








            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.




















            • I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

              – Duncan C
              5 hours ago













            1












            1








            1







            C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.






            share|improve this answer








            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.










            C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.







            share|improve this answer








            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            share|improve this answer



            share|improve this answer






            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            answered 6 hours ago









            VaibhavVaibhav

            592




            592




            New contributor




            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.





            New contributor





            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            Vaibhav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.












            • I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

              – Duncan C
              5 hours ago

















            • I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

              – Duncan C
              5 hours ago
















            I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

            – Duncan C
            5 hours ago





            I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.

            – Duncan C
            5 hours ago











            1














            version using String (not recommended)



            #define LED 2
            const char* a = "abcd";

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            String s = Serial.readStringUntil('n');
            s.trim();
            if (s == a)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);





            the version with C-string:



            #define LED 2
            const char* a = "abcd";
            char buffer[32];

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            size_t l = Serial.readBytesUntil('n', buffer, sizeof(buffer - 1));
            if (buffer[l - 1] == 'r')
            l--;

            buffer[l] = 0; // the terminating zero
            Serial.println(buffer);
            if (strcmp(buffer, a) == 0)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);








            share|improve this answer























            • As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

              – VE7JRO
              3 hours ago















            1














            version using String (not recommended)



            #define LED 2
            const char* a = "abcd";

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            String s = Serial.readStringUntil('n');
            s.trim();
            if (s == a)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);





            the version with C-string:



            #define LED 2
            const char* a = "abcd";
            char buffer[32];

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            size_t l = Serial.readBytesUntil('n', buffer, sizeof(buffer - 1));
            if (buffer[l - 1] == 'r')
            l--;

            buffer[l] = 0; // the terminating zero
            Serial.println(buffer);
            if (strcmp(buffer, a) == 0)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);








            share|improve this answer























            • As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

              – VE7JRO
              3 hours ago













            1












            1








            1







            version using String (not recommended)



            #define LED 2
            const char* a = "abcd";

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            String s = Serial.readStringUntil('n');
            s.trim();
            if (s == a)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);





            the version with C-string:



            #define LED 2
            const char* a = "abcd";
            char buffer[32];

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            size_t l = Serial.readBytesUntil('n', buffer, sizeof(buffer - 1));
            if (buffer[l - 1] == 'r')
            l--;

            buffer[l] = 0; // the terminating zero
            Serial.println(buffer);
            if (strcmp(buffer, a) == 0)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);








            share|improve this answer













            version using String (not recommended)



            #define LED 2
            const char* a = "abcd";

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            String s = Serial.readStringUntil('n');
            s.trim();
            if (s == a)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);





            the version with C-string:



            #define LED 2
            const char* a = "abcd";
            char buffer[32];

            void setup()
            Serial.begin(115200);
            pinMode(LED, OUTPUT);


            void loop()
            if (Serial.available())
            size_t l = Serial.readBytesUntil('n', buffer, sizeof(buffer - 1));
            if (buffer[l - 1] == 'r')
            l--;

            buffer[l] = 0; // the terminating zero
            Serial.println(buffer);
            if (strcmp(buffer, a) == 0)
            digitalWrite(LED, HIGH);
            else
            digitalWrite(LED, LOW);









            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 4 hours ago









            JurajJuraj

            8,19621128




            8,19621128












            • As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

              – VE7JRO
              3 hours ago

















            • As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

              – VE7JRO
              3 hours ago
















            As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

            – Edgar Bonet
            4 hours ago





            As I already commented on VE7JRO's post, Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

            – Edgar Bonet
            4 hours ago













            The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

            – VE7JRO
            3 hours ago





            The String version works perfectly, but I can't get the C-string version to work. For me, the serial monitor shows "abcd" written out to 2 lines: line 1 prints "ab", line 2 prints "cd". Perhaps it's the old version of the IDE I'm using (1.0.6.2). I like that you provided 2 example sketches so the OP can see the difference in compile size: String 4364 bytes VS C-string 2746 bytes.

            – VE7JRO
            3 hours ago











            0














            Here is a test sketch that uses a char array VS the String object. Please remember to set the serial monitor to send a newline only.



            char inputBuffer[16];
            char compareToThisString[] = "test string";

            void setup()
            Serial.begin(9600);


            void loop()

            if(Serial.available() > 0)

            Serial.readBytesUntil('n', inputBuffer, 16);

            if(strcmp(compareToThisString, inputBuffer) == 0)
            Serial.println("Matches");

            else
            Serial.println("No Match");


            memset(inputBuffer, 0, sizeof(inputBuffer));



            As Egar Bonet mentions in his comments, there is a (up to) one second delay before Serial.readBytesUntil() terminates. That does not apply to the sketch I've written because the function terminates as soon as it receives the n character. Serial.readBytesUntil() is blocking code, but that is a different matter which may or may not be an issue for you, depending on what you're building and how much data you are sending. To reduce the timeout period, there is a Serial.setTimeout() function which could be set to whatever you want, but it only comes into play if you don't send the n character.






            share|improve this answer

























            • why the memset?

              – Juraj
              4 hours ago






            • 1





              read max 15 to have one zero left in the array

              – Juraj
              4 hours ago











            • I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

              – VE7JRO
              4 hours ago











            • Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

              – VE7JRO
              4 hours ago















            0














            Here is a test sketch that uses a char array VS the String object. Please remember to set the serial monitor to send a newline only.



            char inputBuffer[16];
            char compareToThisString[] = "test string";

            void setup()
            Serial.begin(9600);


            void loop()

            if(Serial.available() > 0)

            Serial.readBytesUntil('n', inputBuffer, 16);

            if(strcmp(compareToThisString, inputBuffer) == 0)
            Serial.println("Matches");

            else
            Serial.println("No Match");


            memset(inputBuffer, 0, sizeof(inputBuffer));



            As Egar Bonet mentions in his comments, there is a (up to) one second delay before Serial.readBytesUntil() terminates. That does not apply to the sketch I've written because the function terminates as soon as it receives the n character. Serial.readBytesUntil() is blocking code, but that is a different matter which may or may not be an issue for you, depending on what you're building and how much data you are sending. To reduce the timeout period, there is a Serial.setTimeout() function which could be set to whatever you want, but it only comes into play if you don't send the n character.






            share|improve this answer

























            • why the memset?

              – Juraj
              4 hours ago






            • 1





              read max 15 to have one zero left in the array

              – Juraj
              4 hours ago











            • I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

              – VE7JRO
              4 hours ago











            • Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

              – VE7JRO
              4 hours ago













            0












            0








            0







            Here is a test sketch that uses a char array VS the String object. Please remember to set the serial monitor to send a newline only.



            char inputBuffer[16];
            char compareToThisString[] = "test string";

            void setup()
            Serial.begin(9600);


            void loop()

            if(Serial.available() > 0)

            Serial.readBytesUntil('n', inputBuffer, 16);

            if(strcmp(compareToThisString, inputBuffer) == 0)
            Serial.println("Matches");

            else
            Serial.println("No Match");


            memset(inputBuffer, 0, sizeof(inputBuffer));



            As Egar Bonet mentions in his comments, there is a (up to) one second delay before Serial.readBytesUntil() terminates. That does not apply to the sketch I've written because the function terminates as soon as it receives the n character. Serial.readBytesUntil() is blocking code, but that is a different matter which may or may not be an issue for you, depending on what you're building and how much data you are sending. To reduce the timeout period, there is a Serial.setTimeout() function which could be set to whatever you want, but it only comes into play if you don't send the n character.






            share|improve this answer















            Here is a test sketch that uses a char array VS the String object. Please remember to set the serial monitor to send a newline only.



            char inputBuffer[16];
            char compareToThisString[] = "test string";

            void setup()
            Serial.begin(9600);


            void loop()

            if(Serial.available() > 0)

            Serial.readBytesUntil('n', inputBuffer, 16);

            if(strcmp(compareToThisString, inputBuffer) == 0)
            Serial.println("Matches");

            else
            Serial.println("No Match");


            memset(inputBuffer, 0, sizeof(inputBuffer));



            As Egar Bonet mentions in his comments, there is a (up to) one second delay before Serial.readBytesUntil() terminates. That does not apply to the sketch I've written because the function terminates as soon as it receives the n character. Serial.readBytesUntil() is blocking code, but that is a different matter which may or may not be an issue for you, depending on what you're building and how much data you are sending. To reduce the timeout period, there is a Serial.setTimeout() function which could be set to whatever you want, but it only comes into play if you don't send the n character.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 4 hours ago

























            answered 5 hours ago









            VE7JROVE7JRO

            1,65151122




            1,65151122












            • why the memset?

              – Juraj
              4 hours ago






            • 1





              read max 15 to have one zero left in the array

              – Juraj
              4 hours ago











            • I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

              – VE7JRO
              4 hours ago











            • Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

              – VE7JRO
              4 hours ago

















            • why the memset?

              – Juraj
              4 hours ago






            • 1





              read max 15 to have one zero left in the array

              – Juraj
              4 hours ago











            • I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

              – VE7JRO
              4 hours ago











            • Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

              – Edgar Bonet
              4 hours ago











            • "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

              – VE7JRO
              4 hours ago
















            why the memset?

            – Juraj
            4 hours ago





            why the memset?

            – Juraj
            4 hours ago




            1




            1





            read max 15 to have one zero left in the array

            – Juraj
            4 hours ago





            read max 15 to have one zero left in the array

            – Juraj
            4 hours ago













            I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

            – VE7JRO
            4 hours ago





            I'm using memset() to "zero out" the input buffer after each use. Without memset(), if you type in the correct string, it matches. If you then type in just the first 4 letter of the string, it matches which is incorrect. Using memset() only cost an extra 10 bytes compile size.

            – VE7JRO
            4 hours ago













            Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

            – Edgar Bonet
            4 hours ago





            Stream::readBytesUntil() will wait for the terminating character until it gets it or it times out, which can lead to long delays during which the sketch is unresponsive. A better solution is to read only whatever is available, and process the buffer when an LF is read. C.f. the blog post Reading Serial on the Arduino, by Majenko, for a better solution.

            – Edgar Bonet
            4 hours ago













            "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

            – VE7JRO
            4 hours ago





            "read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacing memset() with this: inputBuffer[0] = ''; doesn't work either.

            – VE7JRO
            4 hours ago










            Iulian Chirvasa is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Iulian Chirvasa is a new contributor. Be nice, and check out our Code of Conduct.












            Iulian Chirvasa is a new contributor. Be nice, and check out our Code of Conduct.











            Iulian Chirvasa is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Arduino Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2farduino.stackexchange.com%2fquestions%2f63106%2fhow-to-compare-a-string%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

            На ростанях Змест Гісторыя напісання | Месца дзеяння | Час дзеяння | Назва | Праблематыка трылогіі | Аўтабіяграфічнасць | Трылогія ў тэатры і кіно | Пераклады | У культуры | Зноскі Літаратура | Спасылкі | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 зменаАкадэмік МІЦКЕВІЧ Канстанцін Міхайлавіч (Якуб Колас) Прадмова М. І. Мушынскага, доктара філалагічных навук, члена-карэспандэнта Нацыянальнай акадэміі навук Рэспублікі Беларусь, прафесараНашаніўцы ў трылогіі Якуба Коласа «На ростанях»: вобразы і прататыпы125 лет Янке МавруКнижно-документальная выставка к 125-летию со дня рождения Якуба Коласа (1882—1956)Колас Якуб. Новая зямля (паэма), На ростанях (трылогія). Сулкоўскі Уладзімір. Радзіма Якуба Коласа (серыял жывапісных палотнаў)Вокладка кнігіІлюстрацыя М. С. БасалыгіНа ростаняхАўдыёверсія трылогііВ. Жолтак У Люсiнскай школе 1959

            Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп