How to compare a stringHow to get string parts from string?How to writte simple string compare?I2C_Anything String / Char Array issuesHow to append float value of into a string ?How to convert String to Double?compare uint8_t to char arrayWebSocket client for ArduinoHttpClient conditional if with readString() incoming data bufferHaving problems with I2C - Slave is receiving “b ~ ,,,”How to compare two string?String compare when using Serial
How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?
Alternative to sending password over mail?
Rock identification in KY
Is it unprofessional to ask if a job posting on GlassDoor is real?
Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?
I'm flying to France today and my passport expires in less than 2 months
Why is 150k or 200k jobs considered good when there's 300k+ births a month?
Can I ask the recruiters in my resume to put the reason why I am rejected?
Why is Minecraft giving an OpenGL error?
Unable to deploy metadata from Partner Developer scratch org because of extra fields
How does quantile regression compare to logistic regression with the variable split at the quantile?
Cross compiling for RPi - error while loading shared libraries
What are the disadvantages of having a left skewed distribution?
"You are your self first supporter", a more proper way to say it
Are astronomers waiting to see something in an image from a gravitational lens that they've already seen in an adjacent image?
Maximum likelihood parameters deviate from posterior distributions
Replacing matching entries in one column of a file by another column from a different file
DC-DC converter from low voltage at high current, to high voltage at low current
Was any UN Security Council vote triple-vetoed?
Does detail obscure or enhance action?
Paid for article while in US on F-1 visa?
Two films in a tank, only one comes out with a development error – why?
What is the word for reserving something for yourself before others do?
Can a vampire attack twice with their claws using Multiattack?
How to compare a string
How to get string parts from string?How to writte simple string compare?I2C_Anything String / Char Array issuesHow to append float value of into a string ?How to convert String to Double?compare uint8_t to char arrayWebSocket client for ArduinoHttpClient conditional if with readString() incoming data bufferHaving problems with I2C - Slave is receiving “b ~ ,,,”How to compare two string?String compare when using Serial
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?
c string
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.
add a comment |
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?
c string
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
Apr 2 at 17:49
add a comment |
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?
c string
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?
c string
c string
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.
edited 2 days ago
chicks
1497
1497
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 Apr 2 at 16:25
Iulian ChirvasaIulian Chirvasa
132
132
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
Apr 2 at 17:49
add a comment |
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
Apr 2 at 17:49
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
Apr 2 at 17:49
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
Apr 2 at 17:49
add a comment |
4 Answers
4
active
oldest
votes
version using String (not recommended, but it makes simpler to understand the following C-string version)
#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);
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
Apr 2 at 19:44
TheStringversion works perfectly, but I can't get theC-stringversion 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:String4364 bytes VSC-string2746 bytes.
– VE7JRO
Apr 2 at 20:28
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If yourloop()takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context.Stream::readBytesUntil()anddelay()work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.
– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
add a comment |
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.
add a comment |
C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.
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
Apr 2 at 18:33
add a comment |
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.
I'm usingmemset()to "zero out" the input buffer after each use. Withoutmemset(), 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. Usingmemset()only cost an extra 10 bytes compile size.
– VE7JRO
Apr 2 at 19:38
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
Apr 2 at 19:43
"read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacingmemset()with this:inputBuffer[0] = '';doesn't work either.
– VE7JRO
Apr 2 at 19:43
readBytesUntilreturns the count of bytes read. it is the position where the 0 should go
– Juraj
2 days ago
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
version using String (not recommended, but it makes simpler to understand the following C-string version)
#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);
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
Apr 2 at 19:44
TheStringversion works perfectly, but I can't get theC-stringversion 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:String4364 bytes VSC-string2746 bytes.
– VE7JRO
Apr 2 at 20:28
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If yourloop()takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context.Stream::readBytesUntil()anddelay()work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.
– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
add a comment |
version using String (not recommended, but it makes simpler to understand the following C-string version)
#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);
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
Apr 2 at 19:44
TheStringversion works perfectly, but I can't get theC-stringversion 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:String4364 bytes VSC-string2746 bytes.
– VE7JRO
Apr 2 at 20:28
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If yourloop()takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context.Stream::readBytesUntil()anddelay()work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.
– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
add a comment |
version using String (not recommended, but it makes simpler to understand the following C-string version)
#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);
version using String (not recommended, but it makes simpler to understand the following C-string version)
#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);
edited 2 days ago
answered Apr 2 at 19:30
JurajJuraj
8,24921128
8,24921128
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
Apr 2 at 19:44
TheStringversion works perfectly, but I can't get theC-stringversion 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:String4364 bytes VSC-string2746 bytes.
– VE7JRO
Apr 2 at 20:28
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If yourloop()takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context.Stream::readBytesUntil()anddelay()work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.
– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
add a comment |
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
Apr 2 at 19:44
TheStringversion works perfectly, but I can't get theC-stringversion 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:String4364 bytes VSC-string2746 bytes.
– VE7JRO
Apr 2 at 20:28
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If yourloop()takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context.Stream::readBytesUntil()anddelay()work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.
– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
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
Apr 2 at 19:44
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
Apr 2 at 19:44
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
Apr 2 at 20:28
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
Apr 2 at 20:28
1
1
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
@EdgarBonet, it will wait only if terminating character is not present. the timeout can be set to for example to 10 milliseconds with setTimeout. in many cases it is better to wait for the stream as continue with other things in loop and then return to read an overflowed buffer
– Juraj
2 days ago
If your
loop() takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context. Stream::readBytesUntil() and delay() work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.– Edgar Bonet
yesterday
If your
loop() takes so long that the serial buffer overflows, then you have probably done something very wrong. You can only afford to wait for the whole message to be received if you have no time-sensitive code outside of interrupt context. Stream::readBytesUntil() and delay() work in the same team: they can help you write simpler code if you can afford keeping the CPU busy doing nothing, but their use is not a good programming habit in general.– Edgar Bonet
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
@EdgarBonet, if the gaps between the received bytes are microseconds small, but available() would sometimes return 0, what is a good way to read a command from Stream? the sketch has nothing to do, until this command is received. Other case: with networking done in external modules and with Arduino libraries you can't have a 'real-time' loop. it could take some seconds until a web server sends a response, but then the bytes go in fast and always more than the serial buffer size.
– Juraj
yesterday
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Apr 2 at 16:57
Duncan CDuncan C
1,9801618
1,9801618
add a comment |
add a comment |
C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.
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
Apr 2 at 18:33
add a comment |
C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.
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
Apr 2 at 18:33
add a comment |
C has strcmp() function that is used to compare two strings. It will return zero if two strings are equal non zero when not.
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.
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.
answered Apr 2 at 17:37
VaibhavVaibhav
803
803
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
Apr 2 at 18:33
add a comment |
I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.
– Duncan C
Apr 2 at 18:33
I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.
– Duncan C
Apr 2 at 18:33
I started to suggest the same thing, and then noticed that the OP is using Arduino String objects, not C strings.
– Duncan C
Apr 2 at 18:33
add a comment |
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.
I'm usingmemset()to "zero out" the input buffer after each use. Withoutmemset(), 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. Usingmemset()only cost an extra 10 bytes compile size.
– VE7JRO
Apr 2 at 19:38
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
Apr 2 at 19:43
"read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacingmemset()with this:inputBuffer[0] = '';doesn't work either.
– VE7JRO
Apr 2 at 19:43
readBytesUntilreturns the count of bytes read. it is the position where the 0 should go
– Juraj
2 days ago
add a comment |
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.
I'm usingmemset()to "zero out" the input buffer after each use. Withoutmemset(), 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. Usingmemset()only cost an extra 10 bytes compile size.
– VE7JRO
Apr 2 at 19:38
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
Apr 2 at 19:43
"read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacingmemset()with this:inputBuffer[0] = '';doesn't work either.
– VE7JRO
Apr 2 at 19:43
readBytesUntilreturns the count of bytes read. it is the position where the 0 should go
– Juraj
2 days ago
add a comment |
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.
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.
edited Apr 2 at 20:12
answered Apr 2 at 19:13
VE7JROVE7JRO
1,65151122
1,65151122
I'm usingmemset()to "zero out" the input buffer after each use. Withoutmemset(), 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. Usingmemset()only cost an extra 10 bytes compile size.
– VE7JRO
Apr 2 at 19:38
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
Apr 2 at 19:43
"read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacingmemset()with this:inputBuffer[0] = '';doesn't work either.
– VE7JRO
Apr 2 at 19:43
readBytesUntilreturns the count of bytes read. it is the position where the 0 should go
– Juraj
2 days ago
add a comment |
I'm usingmemset()to "zero out" the input buffer after each use. Withoutmemset(), 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. Usingmemset()only cost an extra 10 bytes compile size.
– VE7JRO
Apr 2 at 19:38
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
Apr 2 at 19:43
"read max 15 to have one zero left in the array". I just tried it, and it doesn't work :( Replacingmemset()with this:inputBuffer[0] = '';doesn't work either.
– VE7JRO
Apr 2 at 19:43
readBytesUntilreturns the count of bytes read. it is the position where the 0 should go
– Juraj
2 days 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
Apr 2 at 19:38
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
Apr 2 at 19:38
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
Apr 2 at 19:43
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
Apr 2 at 19:43
"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
Apr 2 at 19:43
"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
Apr 2 at 19:43
readBytesUntil returns the count of bytes read. it is the position where the 0 should go– Juraj
2 days ago
readBytesUntil returns the count of bytes read. it is the position where the 0 should go– Juraj
2 days ago
add a comment |
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.
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
Apr 2 at 17:49