Send a String Out and Read One in Arduino
Overview of this Chapter
- 1Working with Text: Strings!
- twoArray of Char (string)
- 3Assigning a new text to a cord
- fourEscape Characters or ... Special Characters
- 5Graphic symbol versus Cord or Single Quote versus Double Quote
- 6Other Array Functions: strlen, sizeof, strcat
- strlen()
- sizeof()
- strcat()
- Instance of strlen, sizeof, strcat
- 7String Object (String with capital letter "S")
- Objects
- The "String" Object
- 8String object Methods (functions)
- Length(), Concat() and convert numbers
- 9Comparing Strings
- string - array of char
- String - object
A complete overview of this course tin be found here: Form Overview.
Working with Text: Strings!
It's all overnice and dandy to work with booleans and numbers, simply we also demand to work with text to communicate.
Granted, the Arduino doesn't accept much use for text when used on it'south own. It has no brandish. Merely a brandish can be attached, or text can be transport/received through the series port and other ways of advice.
Nosotros take used strings already a few times. Each time when we used a " Serial.print ( )
" or " Serial.println ( )
", nosotros actually already used strings. Remember that a text in C needs to be enclosed in double quotes? That would brand it a cord.
But to work well with strings, we demand to understand what a string really is.
First of all, we can use a "cord" (all lowercase!) – where a string is a so called array of characters. In English that makes sense: information technology'due south a "list" of characters.
The 2nd way of working with strings is past using the "String" object (discover the upper-case letter "S"?).
Both volition exist discussed and shown to you in the next paragraphs and capacity …
Ad Blocking Detected
Please consider disabling your ad blocker for our website.
We rely on these ads to be able to run our website.
You can of course support us in other ways (see Support Us on the left).
Array of Char (string)
An "assortment" (Array Data Type, Assortment Information Structure) tin can be seen as a collection of elements of the aforementioned data type.
Run into it, in it's simplest form, as a listing. In the case of a string: a list of char(acters).
A string (all lower case !!!) is anARRAY OF CHARACTERS
The variable that we define, actually points to the first item in the array – or amend said: it points to the memory location of the showtime particular.
In the case of a string, the array keeps going, until your Arduino finds a Null character. The Zilch character terminates the cord – or indicates the end of the string.
Say what now?
Yep, a Zippo, a cypher. There is a special graphic symbol defined for this (see our graphic symbol list).
Information technology'southward character zero. But we do not (yet) have to worry most that – but it is something to keep in listen. Since strings are quite often used, the linguistic communication "C" which we use for Arduino Programming, comes with a standard library of string related functions, which handle quite a lot already automatically.
Another thing to continue in heed is that arrays start counting with "0" for item 1, "ane" for item ii, etc.
This is chosen zero indexed or naught based numbering – counting starts with zero.
A string (Array of Characters), is terminated by a NULL character.
Arrays are Cypher INDEXED, which ways they start counting with cipher.
And so an example could be: string Name = "Hans";
Nevertheless, that doesn't work … you'll become an error bulletin that "string" was not defined.
The correct fashion to define a string would be: char Proper name[ ] = "Hans" ;
What this does, is create an array of characters (which is a string), the empty square brackets basically says "compiler! Get effigy out yourself how large this assortment should be". If we would have entered a number, then that number should at least exist big enough to agree our string plus one Naught character.
In the example that would exist 4 characters for our text and a fifth character for the Zippo grapheme.
We can too define a cord with a stock-still length similar this: char Name[ 5 ] = "Hans" ;
Note that if the number is bigger than the number of characters we need, then this will work just fine. However, your Arduino might allocate the extra characters as well and waste product retentivity space as we're not using information technology. On the other hand, if you lot look the cord to modify in the program and all those characters might be needed, so you'd already exist prepared.
If this number would be too depression, and so your compiler volition mutter and evidence an mistake message.
Leaving length the string assortment (char variablename[] = "…") undefined volition make that the compiler determines the required size of the array – one time only!
Accessing an Element of an Array outside of the length of the array can cause unexpected results, mistake letters or fifty-fifty crashes of your application!
In either case, information technology will outcome in this:
position (index) | Content of memory slot |
---|---|
0 | H |
1 | a |
ii | n |
3 | s |
4 | NULL |
The variable "Name" points to the memory location of the "H" character of the string, which is at position 0 (zero) and therefor has "0" as it'southward alphabetize number.
We can actually retrieve that character. For example "Proper name[ii]" would result in an "north", "Name[0]" would render a "H", etc.
If we send address the whole variable, "Name", then it would return the address of "Name[0]" but your program volition go along pulling up the next index, and the next, and the next, until it reaches that Naught character. Then in the finish, it will render the text of the cord.
char Proper noun[ ] = "Hans" ;
Serial.println (Name[ 2 ] ) ; // prints "n"
Serial.println (Name[ 0 ] ) ; // prints "H"Serial.println (Proper noun) ;// prints "Hans"
Now nosotros tin can really assign a different character to an chemical element (or item) in an array.
Assigning a new text to a string
We now know about variables and strings, and nosotros know how to ascertain a string and assign it an initial value.
What if we want to alter the cord, for case, supercede in "Hans" in our string with "Bram"?
Strangely enough, the following doesnot work: Name = "Bram" ;
The Arduino compiler volition requite yous the error message "invalid array assignment". But a string is a string right?
Not really. Remember how I said before that the variable (in our example "Name") actually points to the memory location of the first element in the array? It'southward a retentiveness address, which is non the same as a string. Believe me, this is something yous'll see quite often, and it's 1 of the reason why I'thou not a fan of the C-language (I'thousand more than of a Pascal fan – and plenty of people will argue with me on that one).
Unfortunately this makes things more than complicated, and nosotros'd have to assign each character to the proper element. Give thanks goodness there is a role for that: strcpy ( )
.
This part, read it as "String Copy", takes ii parameters.
The destination where the string should be copied to, and the source where the cord is coming from.
The destination should exist a variable, it has to exist able to "receive" the information, then it has to be the proper data type every bit well.
The source tin can be a variable, a constant, or a string (tekst between double quotes).
An case on how to use this, see line 12 where we employ strcopy :
one
2
3
4
5
6
vii
8
9
10
11
12
xiii
xiv
15
sixteen
17
18
nineteen
20
21
22
void setup( ) {
// gear up the speed for the serial monitor:
Series.begin ( 9600 ) ;char Name[ ] = "Hans" ;
Serial.println (Name[ ii ] ) ; // prints "due north"
Serial.println (Name[ 0 ] ) ; // prints "H"Serial.println (Name) ;// prints "Hans"
strcpy (Proper name, "Bram" ) ;
Serial.println (Proper name[ 2 ] ) ; // prints "a"
Serial.println (Name[ 0 ] ) ; // prints "B"Serial.println (Name) ;// prints "Bram"
}void loop( ) {
// go out empty for now
}
Advertising Blocking Detected
Please consider disabling your advertizing blocker for our website.
We rely on these ads to be able to run our website.
You can of form support united states in other ways (see Support Us on the left).
Escape Characters or … Special Characters
Now sometimes we'd similar to impress for example double quotes, but merely typing them into a cord volition not work – the string would break. The compiler will call back you're done after seeing the 2nd double quotes and everyting remaining will go an unclear mess.
Other special characters are only impossible to type without making things a mess also!
As an example that will fail: Serial.println ( "Hi "guest", welcome to Arduino" ) ;
The colour highlighting of the Arduino IDE's text editor already shows your this …
The code highlighting of the Arduino IDE text editor, volition testify yous if a string "breaks" or non, past changing character colors in the string you only typed.
To actually enter a double quote in a string, we need to utilize an escape character, which in the language C is the backslash (\).
The correct way would be: Series.println ( "Hello \"guest\", welcome to Arduino" ) ;
The following example shows just that:
The first line shows us the wrong manner of doing it. The keywords of importance are printed in orange en the string in a green-similar color. But … our string has a chunk of black text in it. The word "invitee" is black. It means that this is non office of the string, which is caused by the double quotes around the give-and-take "invitee".
Now the second line shows the colors the way they should exist, and for that we removed the double quotes. You come across the entire string being green-ish?
The third line shows u.s.a. the trick with the backslash. We placed them right before the special graphic symbol, then the compiler knows that the next character is special and part of the cord.
Annotation that when y'all want the adjacent graphic symbol to exist special as well, then y'all'd demand to "escape" those also. For example if we add multiple double quotes around the word "guest": Serial.println ( "Hello \" \"guest\" \", welcome to Arduino" ) ;
This trick has to be used for certain other characters equally well, for example starting a new line is an ASCII character (see the graphic symbol tabular array, and wait in the "Esc" column). If we'd like to identify a line break (start a new line) in our string, and so nosotros would need ASCII character ten, which we write equally "\due north".
The most mutual ones are:
Escape "code" | ASCII | Purpose |
---|---|---|
\due north | x | LF (Line Feed) – Showtime new line ( due north ew line) |
\r | 13 | CR (Carriage Return) – Become to beginning of a line ( r eturn) |
\t | nine | Tab – Advance cursor to adjacent tab-stop ( t ab) |
\" | 34 | Double Quote |
\' | 39 | Single Quote |
\\ | 92 | Backslash – then we tin really type that one also |
You do not demand to memorize these, you'll remember them later having used them a few time.
Character versus String or Single Quote versus Double Quote
We take mentioned that we could assign private characters to the array elements of our cord,… so how is that done so?
We have seen that nosotros use double quotes ( " ) to enclose a sequence of characters.
Nosotros tin can fifty-fifty make a cord of zero characters (just: "") or a string of one character ("A").
But these are all strings.
Double quotes are used for strings, which can exist zilch or more than characters.
The post-obit code will not work, when we endeavour to assign a grapheme to i of the retentivity locations of our string (array of char):
Proper noun[ i ] = "H" ; // will generate an error bulletin
The fault message invalid conversion from 'const char*' to 'char'
tells u.s. that nosotros are assigning the wrong kind of datatype to our array element. In simple words: This is because we are trying to assign a cord to a character.
To brand this work, we demand to assign a graphic symbol to the char, instead of a string and for that purpose nosotros apply single quotes ( ' ).
A way to remember this: 1 quote = one character, multiple quotes = multiple characters.
Single quotes are used for char(acters), which is exactly 1 character.
This example will work:
Name[ 1 ] = 'H' ; // this works!
Let's look at the previous instance, and aggrandize information technology a footling. We want to supercede the name "Hans" with the proper noun "Bram".
1
2
3
4
five
half-dozen
7
8
9
ten
eleven
12
xiii
fourteen
15
16
17
18
19
20
21
22
23
24
25
void setup( ) {
// prepare the speed for the serial monitor:
Serial.begin ( 9600 ) ;char Proper noun[ ] = "Hans" ;
Serial.println (Proper noun[ 2 ] ) ; // prints "n"
Serial.println (Name[ 0 ] ) ; // prints "H"Serial.println (Proper name) ;// prints "Hans"
Name[ 0 ] = 'B' ;
Name[ i ] = 'r' ;
Name[ 2 ] = 'a' ;
Proper name[ three ] = 'm' ;Serial.println (Proper noun[ ii ] ) ; // prints "a"
Serial.println (Name[ 0 ] ) ; // prints "B"Series.println (Name) ;// prints "Bram"
}void loop( ) {
// leave empty for now
}
Come across how we have to assign each individual character to each individual array chemical element?
Nosotros tin skip "Name[4]" because information technology already holds the Null character and nosotros do not want to modify that.
However, if our cord becomes shorter, for example by replacing "Hans" with "Max" (my other nephew), so we would need to add the NULL character again:
1
2
three
4
v
6
7
viii
9
ten
11
12
13
xiv
15
16
17
xviii
19
twenty
21
22
23
24
25
void setup( ) {
// set the speed for the serial monitor:
Series.begin ( 9600 ) ;char Name[ ] = "Hans" ;
Series.println (Name[ 2 ] ) ; // prints "n"
Serial.println (Proper name[ 0 ] ) ; // prints "H"Serial.println (Name) ;// prints "Hans"
Proper noun[ 0 ] = 'Thousand' ;
Name[ 1 ] = 'a' ;
Name[ 2 ] = '10' ;
Name[ 3 ] = 0 ;Series.println (Name[ 2 ] ) ; // prints "x"
Series.println (Proper name[ 0 ] ) ; // prints "Thou"Series.println (Name) ;// prints "Max"
}void loop( ) {
// leave empty for now
}
Now "Proper noun[3]" and "Name[4]" are both a Goose egg character, which is equal to naught.
See how nosotros assign a char a number, where nosotros assign the number aught to Proper name[3]?
Instead of assigning information technology a graphic symbol, we tin actually use the ASCII code for a given character.
Run across our character table for those numbers (look at the column "DEC").
And so to compare, an example with characters and the same one with ASCII codes:
// With characters
Proper noun[ 0 ] = 'B' ;
Name[ 1 ] = 'r' ;
Proper name[ two ] = 'a' ;
Proper noun[ 3 ] = 'yard' ;// With ASCII codes
Name[ 0 ] = 66 ;// = 'B'
Name[ 1 ] = 114 ; // = 'r'
Proper name[ ii ] = 97 ;// = 'a'
Name[ 3 ] = 109 ; // = 'm'
Obviously, using ASCII is non the obvious way to do information technology when you'd like to assign text to a string. However, at that place are scenario's where this can be very applied. I'll illustrate this with a quick nonesense example, which quickly lists all the letters of the alphabet, where we can apply a "for" loop to count from 65 (=A) to xc (=Z).
The "for" loop can be used with numbers, or basically annihilation nosotros can enumerate, or in other words: Data types that we can count with stock-still increments, or whole numbers. For case, a byte, or an integer (both whole numbers):
1
2
3
four
five
half-dozen
seven
8
9
x
11
12
13
14
15
void setup( ) {
// set the speed for the series monitor:
Serial.begin ( 9600 ) ;char Alphabetic character[ ] = " " ;
for (byte A= 65 ; A<= 90 ; A++ ) {
Letter[ 0 ] = A;
Serial.println (Alphabetic character[ 0 ] ) ;
}
}void loop( ) {
// exit empty for now
}
At present that nosotros know that characters are done with unmarried quotes, nosotros could also do this with this kind of loop.
Just keep in mind that achar tin can be "counted" equally well, and this actually does work (see code below). Char is in essence a "byte", and as nosotros just have seen, we tin can assign it a number – so char can be counted also, as if it's a whole "number".
Note: don't forget that nosotros are counting chars – then we must use single quotes!
one
2
3
four
5
half dozen
7
8
9
10
11
12
13
14
15
void setup( ) {
// ready the speed for the serial monitor:
Serial.begin ( 9600 ) ;char Letter[ ] = " " ;
for ( char A= 'A' ; A<= 'Z' ; A++ ) {
Letter[ 0 ] = A;
Serial.println (Letter of the alphabet[ 0 ] ) ;
}
}void loop( ) {
// leave empty for at present
}
In both examples the output will be the alphabet in uppercase characters.
Ad Blocking Detected
Please consider disabling your advertisement blocker for our website.
We rely on these ads to be able to run our website.
Yous tin can of course back up us in other ways (see Support Us on the left).
Other Assortment Functions: strlen, sizeof, strcat
We accept seen that part "strcpy()" (read that as "string Copy"). There are a few applied other functions we should mention.
strlen()
"strlen()" (read every bit: String Length) takes one parameter, a string, and returns the number of characters in the string. It volition nonetheless non count the NULL graphic symbol at the end.
sizeof()
"sizeof()" does the same thing as "strlen()", nonetheless it will include the NULL grapheme in it'south count. It actually returns the size of the total array, fifty-fifty if it would be filled with Nil characters.
strcat()
"strcat()" is an odd i, it will add a string at the terminate of a given string variable. Read this i as "Cord Concatenate".
Example of strlen, sizeof, strcat
Permit's gum these 4 functions together in an example, so yous go an idea.
i
2
3
iv
v
6
7
8
9
10
xi
12
xiii
14
15
16
17
18
19
xx
21
22
23
24
25
26
27
28
29
xxx
31
32
33
34
35
36
37
38
void setup( ) {
// set the speed for the serial monitor:
Serial.begin ( 9600 ) ;char Name[ 45 ] = "Hans" ;
int count = 0 ;Serial.impress ( "Name = " ) ;
Series.println (Name) ;// determine length
count = strlen (Proper noun) ;
Series.impress ( "Length of Name with strlen: " ) ;
Series.println (count) ;// determine array size
count = sizeof (Name) ;
Serial.print ( "Length of Proper noun with sizeof: " ) ;
Serial.println (count) ;strcat (Proper name, " has two nephews, called Bram and Max!" ) ;
Series.impress ( "Name = " ) ;
Series.println (Proper name) ;// determine length
count = strlen (Name) ;
Serial.print ( "Length of Proper name with strlen: " ) ;
Serial.println (count) ;// determine assortment size
count = sizeof (Name) ;
Series.print ( "Length of Proper name with sizeof: " ) ;
Series.println (count) ;
}void loop( ) {
// leave empty for now
}
The resulting output:
Proper name = Hans
Length of Name with strlen: iv
Length of Proper name with sizeof: 45
Name = Hans has two nephews, called Bram and Max!
Length of Proper noun with strlen: 42
Length of Name with sizeof: 45
At present if you remember from before where I said:
- If we do not ascertain the string length, the compiler will make up one's mind/approximate the length i fourth dimension only!
- Accessing elements across the size of the array can give unexpected results.
OK, allow'southward do this intentionally by modifying line 5 to char Name[ ] = "Hans" ;
What this does, is that the compiler will judge the required array space, one time only! This means that information technology will see the string "Hans" and will make up one's mind that these 4 characters volition need an array of 5 characters (text plus Nothing grapheme).
Compile and upload the modified code to your Arduino and yous will run across something goofy happening, for example:
Name = Hans
Length of Proper name with strlen: iv
Length of Name with sizeof: five
phews, called Bram and Max!Hans has ii nephews, called Bram����
Run across the funny characters, and you might notice that your Arduino keeps spitting out funny and weird characters!?
That'south because the array was only 5 characters long.
When we added " has two nephews, called Bram and Max!" to that string/array, we royally exceed the pre-defined space, and your Arduino will try to print that anyway. Not being able to find the NULL character (nosotros have overwritten it with a not-NULL graphic symbol, a infinite-character, in this example), it will keep spitting out any is in memory until it finds a Nada character. Which might exist right away, or never …
Non exactly what we expected to happen right?
And thats the reason why you have to pay attention to the length of an assortment.
String Object (Cord with capital letter "S")
The previous "string" was an Assortment of Char. With a lowercase "s".
The Arduino IDE however, offers some other "Cord" (capital letter "Due south"), which is an object.
The tedious and cumbersome things nosotros had to practise with the old "string" (lowercase: Array of Char), are washed much easier with the "String" (Uppercase "S": an object) object … but what is an object?
Objects
We haven't learned much well-nigh objects yet, even though nosotros accept already used i (Serial).
A very brusque caption of what an "object" is, would be a "matter" or "particular" with backdrop and functions (methods).
An Object is a "thing" with "properties" and "methods" (functions)
Such a "thing" could exist anything, for example a "car".
Let'south continue this simple and assume a car has a color, a working engine, maybe some gas, number of doors, a trunk, and wheels.
These are called "properties", they do non do anything, they're only a given fact, items information technology already has (or could take).
One of those "could have" properties could exist "driver".
Since the car tin be empty (driver == NULL), or a commuter can sit down in the drivers-seat (driver != Naught).
At present a car can motion (driving), park, honk it'due south horn, open or close the trunk, open or close the doors, etc.
These are functions of the object "motorcar". In "object oriented programming" we phone call those " methods ".
Methods actually "do" something, actions you tin do accept the machine exercise or that can be done with the car.
There are several reason why we'd like to apply objects.
For one; everything is logically grouped together. There is no defoliation to what particular the properties or functions vest. So when nosotros aks for properties or telephone call a method (office) of a given object "auto" then we know information technology only relates that that specific car.
Some other reason is that in one case an object has been defined, it actually kind-a behaves like a data type, which can use for variables. Say we have ane "motorcar" and so we create a variable "MyCar" as the object (data type) "car". But if we have a garage filled with cars, so we can re-use that same definition to create multiple variables (MyCar, YourCar, DadsCar, MomsCar), or even an array of cars (Cars[0], Cars[one], Cars[2],…).
Now we won't go into object correct now, only it'due south good to take a bones understanding what an object is.
The "String" (with majuscule "S") and "Serial" are such objects.
With "Series" nosotros have already seen the methods (functions) "begin", "print" and "println". We call these methods to have the object do something , like start communication, or send a cord to our Series Monitor of our Arduino IDE.
Maybe you've now seen that we always telephone call an object in a format like this: OBJECT.METHOD or OBJECT.Holding? We call the object and split object and method (or property) with a menstruation.
The "String" Object
Every bit mentioned and shown earlier: the assortment of char variant of a cord is a lilliputian cumbersome to work with. So the good people at Arduino created an object to make working with strings easier. Again a reminder: it's the "String" with a capital "South"!!!
You will encounter pretty rapidly how much more than powerful the "String" is compared to the "string".
Let'southward commencement with creating a variable of data type "String": Cord Proper noun = "Hans" ;
As we have seen with the quondam "string", nosotros can simply create a variable and assign it a value in 1 unmarried line. Nothing new there, well except for the keyword "Cord" of course and the lack of square brackets.
Similar we take seen with the other "string", we can also utilize "Serial.impress()". So permit's shove this together in a quick example:
ane
2
3
iv
v
half-dozen
vii
eight
9
10
eleven
12
13
void setup( ) {
// set the speed for the serial monitor:
Serial.begin ( 9600 ) ;String Name = "Hans" ;
Serial.print ( "Name = " ) ;
Serial.println (Name) ;
}void loop( ) {
// leave empty for at present
}
Works just like the quondam "string", and the issue in the Serial Monitor will be: Name = Hans
Aught new, and nothing exciting just yet.
Now allow'due south try to change "Hans" to "Bram" in our lawmaking. Nosotros can practise this by assigning a "String" to a "String":
one
ii
iii
4
5
half-dozen
7
8
9
10
11
12
13
xiv
15
xvi
17
18
void setup( ) {
// fix the speed for the serial monitor:
Series.begin( 9600 );String Name = "Hans";
Serial.print( "Proper noun = " );
Serial.println(Name);Name = "Bram";
Series.print( "Proper noun = " );
Serial.println(Name);
}void loop( ) {
// leave empty for now
}
Line 10 could as well exist written as Proper noun = String( "Bram" ) ;
, which volition really piece of work as well, but now we assign the new object (property the cord "Bram") to the old object, versus the method in the code where we assign just a cord to the object.
At least nosotros already come across that assigning new text to "String" is easier.
Now allow's make that cord longer, in the previous instance, when using the array of char "string", nosotros noticed that we had to pay attention to the size of the assortment, so we wouldn't go beyond it's chapters. The "String" object however saves the states that worry. It corrects automatically.
1
two
3
4
5
half-dozen
7
eight
9
10
xi
12
13
14
15
16
17
eighteen
void setup( ) {
// set the speed for the serial monitor:
Serial.begin ( 9600 ) ;Cord Name = "Hans" ;
Serial.print ( "Name = " ) ;
Serial.println (Name) ;Name = "Hans has two nephews, their names are Bram and Max!" ;
Serial.print ( "Proper noun = " ) ;
Series.println (Name) ;
}void loop( ) {
// leave empty for now
}
You see? We tin assign a much larger string than what we started out with, and when press information technology, we feel zero bug. This is already a second signal where the object is easier to use.
So if the "String" object is and then much easier to work with? Then why even bother with the "string" assortment of graphic symbol?
For two reasons. For i, the object will take up more retentiveness, since it has all these fancy properties and methods. Some other reason is that the String object, actually uses the "string" array of characters likewise.
Ad Blocking Detected
Please consider disabling your ad blocker for our website.
We rely on these ads to be able to run our website.
Y'all tin can of course back up us in other ways (see Support Us on the left).
String object Methods (functions)
Now the "String" object, has a lot of methods (functions) we can work with, which can make our life a lot easier when working with strings, and this is where we will really see the ability of objects.
Below an example of some of this trickery … for a full list of available functions, delight take a good wait at the Arduino String Object Reference. It will show yous all the other tricks.
Length(), Concat() and catechumen numbers
In the example below nosotros will concatenate strings, make up one's mind the length of the cord and even add numbers to our string, without any existent effort.
1
2
3
4
v
six
7
8
nine
10
11
12
13
fourteen
fifteen
sixteen
17
xviii
19
20
21
22
23
24
25
26
27
28
29
thirty
31
32
33
34
35
36
37
38
39
40
41
void setup( ) {
// set the speed for the serial monitor:
Serial.begin ( 9600 ) ;String Name = "Hans" ;
Serial.impress ( "Name = " ) ;
Serial.println (Name) ;// make up one's mind length
Serial.print ( "Length of Name with strlen: " ) ;
Serial.println (Name.length ( ) ) ;Proper name.concat ( " has two nephews, called Bram and Max!" ) ;
Serial.print ( "Name = " ) ;
Serial.println (Proper noun) ;// decide length
Serial.print ( "Length of Proper noun with strlen: " ) ;
Series.println (Name.length ( ) ) ;// Alternative way of adding text
Name = "Hans" ; // reset to original text
Serial.print ( "Name = " ) ;
Serial.println (Proper noun) ;Name += " has 2 nephews" ;
Name = Name + ", the are called Bram" + " and Max" ;
Serial.print ( "Name = " ) ;
Series.println (Proper name) ;// this won't work with arrays
Name = "A large number is: " ;
Proper noun = Proper noun + 32768 ;
Serial.print ( "Name = " ) ;
Series.println (Proper noun) ;
}void loop( ) {
// leave empty for at present
}
The output of this code:
Proper noun = Hans
Length of Name with strlen: 4
Proper noun = Hans has two nephews, called Bram and Max!
Length of Name with strlen: 42
Proper noun = Hans
Name = Hans has 2 nephews, the are called Bram and Max
Proper name = A large number is: 32768
Allow's walk through this case.
We create the String object "Name" and assign it the value "Hans" (lines 7 and 8), which we tin can impress with "Serial" as we have seen before. Now in line 12, we retrieve the length of our string – which is just the number of characters in the string, and not including the Aught terminating grapheme. This is done with the "length()" method of the "String" object: Proper noun.length ( )
. This method will return a number, an integer, which we send right away to "Serial.impress".
In line 14, we call the method "concat()" to concatenate " has two nephews, called Bram and Max!" to the original string "Hans". As you can run into, this works right abroad. But … in that location is an easier manner to mucilage an extra string to your "Cord" object past but using the plus symbol (+), even the compound operator "+=" works. See lines 27 and 28, where nosotros employ "+=" and even the regular "+".
The "String" object notwithstanding is even more powerful and tin right abroad convert a number (int in this example) to a string, and replace or adhere information technology to an existing string – see line 34 – which is something we cannot do with the previous "string" array of characters.
Now if we know that String( "some text" )
returns a "String" object, and we know that we can glue strings together with the plus symbol (+), and we know that "Serial.println()" take a "String" as a parameter,… then nosotros can do some tricks to save usa the hassle of writing 2 "Serial" lines (print() and println()) whenever we want to print values or variables.
1
two
3
4
v
six
seven
Serial.println (String( "Number seven = " ) +String( 7 ) ) ;
int test = 10 ;
Serial.println (Cord( "How many fingers exercise I have? " ) +String(test) ) ;Series.println (String( "X = " ) +
String(test) ) ;
The first line should be dissected as:
– Create a String object holding the string "Number 7 = ",
– Create a String object property the cord of the value seven,
– Glue these two object together (+),
– Laissez passer the resulting String object to the "Serial.println()" method (function).
And the result will be exactly what nosotros desire, the Series Monitor will print "Number seven = 7".
In line 3 we ascertain an integer (int) variable chosen "test".
In line 4 nosotros come across an instance similar to line 1, just in this case nosotros are not using a value (seven) but a variable (exam), which works besides.
Now in lines 6 and 7 nosotros see something new, and this has nothing to do with strings or objects.
Call up we said way dorsum that we cease a statement with a semicolon?
In line 6 we did not exercise that, so the compiler assumes that the statement isn't done yet and continues on the next line.
The advantage is that breaking a statement like this over multiple lines actually makes your code more readable.
At present try this case. Simply copy the code in the "setup()" function. Run across if you can practise this on your ain.
Comparing Strings
Now printing and calculation strings is all nice and dandy. But can nosotros use strings to compare? Well, yes nosotros can!
string – array of char
With the array of character "string", we observe something weird. It fails to compare …
We would await it to say "Hello Hans", since "Hans" == "Hans", right? …
1
two
3
iv
5
vi
seven
eight
9
10
eleven
12
13
fourteen
15
16
17
18
nineteen
20
21
void setup( ) {
// ready the speed for the serial monitor:
Serial.begin ( 9600 ) ;char Proper name[ ] = "Hans" ;
Series.impress ( "Proper noun = " ) ;
Serial.println (Name) ;if (Proper noun== "Hans" ) {
Serial.println ( "Hullo Hans" ) ;
}
else
{
Serial.println ( "You are not Hans" ) ;
}
}void loop( ) {
// go out empty for now
}
The reason why this fails, is because we are comparing a string with the retention location "pointer" of an array. Which will non be the same obviuosly. We actually demand to utilize a special office for this: "strcmp()" (read that as "cord compare")
1
2
iii
4
5
6
7
viii
ix
x
11
12
xiii
14
15
16
17
18
19
20
21
void setup( ) {
// prepare the speed for the serial monitor:
Serial.brainstorm ( 9600 ) ;char Name[ ] = "Hans" ;
Serial.print ( "Name = " ) ;
Serial.println (Name) ;if ( strcmp (Proper noun, "Hans" ) == 0 ) {
Series.println ( "Hello Hans" ) ;
}
else
{
Series.println ( "You lot are non Hans" ) ;
}
}void loop( ) {
// leave empty for now
}
The office "strcmp()" returns a aught when both strings are the aforementioned.
This functions returns a number less than aught when the first cord is smaller than the second string, or returns a number greater than null when the get-go string is larger than the second string.
But there is a catch …
When comparison the two strings, information technology will actually compare the ASCII values. So when information technology returns a number greater than zero, it actually means that it ran into a character which has a greater ASCII value compared to the other grapheme, in the same position in the other string, and this tin can be disruptive, because we humans would expect "Hans" to be greater than "Hi" – but its non. This is in part also considering nosotros humans encounter the longer cord "Hans" every bit the larger one of the two.
When comparing "Hans" and "Howdy", things become fine with the first character – they are the same.
The second characters, "a" (ASCII: 97) and "i"(ASCII: 105), even so, will crusade an unexpected (human) response.
"strcmp("Hans", "Hullo")" will result in a negative number … and so "Hans" is smaller than "Hi".
strcmp() is best used to see if ii strings are identical (returns cypher)
or not identical (returns is not zero)
Let's expect at an example that shows this unexpected behavior:
1
2
3
4
5
half-dozen
seven
8
9
10
11
12
xiii
14
15
16
17
18
19
20
21
void setup( ) {
// set the speed for the serial monitor:
Serial.brainstorm ( 9600 ) ;// compare
Serial.print ( "strcmp(\"Hans\",\"Hans\") = " ) ;
Serial.println ( strcmp ( "Hans" , "Hans" ) ) ;Serial.print ( "strcmp(\"Hans\",\"Hansie\") = " ) ;
Serial.println ( strcmp ( "Hans" , "Hansie" ) ) ;Serial.print ( "strcmp(\"Hans\",\"Howdy\") = " ) ;
Serial.println ( strcmp ( "Hans" , "Hi" ) ) ;Serial.print ( "strcmp(\"Hans\",\"Haa\") = " ) ;
Serial.println ( strcmp ( "Hans" , "Haa" ) ) ;
}void loop( ) {
// go out empty for now
}
The output:
strcmp("Hans","Hans") = 0
strcmp("Hans","Hansie") = -1
strcmp("Hans","Hi") = -1
strcmp("Hans","Haa") = ane
Then nosotros run across that "Hans" is smaller than "Hansie", as we humans would await.
Unexpected, but "Hans" is also smaller than "How-do-you-do", even though nosotros humans wait the longer string to be the larger one.
So if you're looking for which string is longer, you'd meliorate compare the length of both strings.
This makes me follow the simple rule that "strcmp()" is best used to see if ii strings are identical.
In the example code yous might have noticed an excellent case of the before mentioned "Escape character" in our strings,….
Cord – object
Comparing "Cord" objects result in the aforementioned kind of defoliation, simply instead of using the "strcmp()" role, we can use the unproblematic comparison operators.
I therefor ordinarily only use to see if two Strings are identical (==) or not equal (!=) to each other.
1
ii
iii
4
5
6
vii
8
9
x
xi
12
thirteen
14
15
sixteen
17
18
19
20
21
22
23
24
25
26
void setup( ) {
// set the speed for the serial monitor:
Serial.brainstorm ( 9600 ) ;String Name = "Hans" ;
Serial.print ( "Name = " ) ;
Serial.println (Name) ;// compare
Serial.impress ( "Equal: "Hans","Hans" = " ) ;
Serial.println (Name == String( "Hans" ) ) ;Serial.print ( "Greater than: "Hans","Hansie" = " ) ;
Serial.println (Proper name > String( "Hansie" ) ) ;Series.print ( "Less than: "Hans","Hello" = " ) ;
Serial.println (Name < Cord( "Hullo" ) ) ;Serial.print ( "Not equal: "Hans","Haa" = " ) ;
Serial.println (Proper name != String( "Haa" ) ) ;
}void loop( ) {
// get out empty for at present
}
So the uncomplicated example we started with (for array of char strings) really does work for the object String:
one
2
3
4
5
6
7
8
9
10
11
12
thirteen
fourteen
15
sixteen
17
18
19
20
21
void setup( ) {
// set up the speed for the serial monitor:
Serial.begin ( 9600 ) ;String Proper noun = "Hans" ;
Serial.print ( "Proper name = " ) ;
Serial.println (Name) ;if (Name == "Hans" ) {
Serial.println ( "Hello Hans" ) ;
}
else
{
Serial.println ( "You are non Hans" ) ;
}
}void loop( ) {
// go out empty for at present
}
If you have questions, just ask them below in the comment section, and continue in mind: There are no stupid questions! We all had to starting time at some point!
Adjacent chapter: Arduino Programming for Beginners – Part eight: Arrays
Source: https://www.tweaking4all.com/hardware/arduino/arduino-programming-course/arduino-programming-part-7/
0 Response to "Send a String Out and Read One in Arduino"
Post a Comment