SlideShare uma empresa Scribd logo
1 de 30
Programming in
Arduino
PART 2
BY: NIKET CHANDRAWANSHI
HTTP://WWW.NIKETCHANDRAWANSHI.ME/
Control Statements
Decision making structures
require that the programmer
specify one or more conditions
to be evaluated or tested by
the program. It should be along
with a statement or statements
to be executed if the condition
is determined to be true, and
optionally, other statements to
be executed if the condition is
determined to be false.
• If statement
• If …else statement
• If…else if …else statement
• switch case statement
• Conditional Operator ? :
if statement
It takes an expression in
parenthesis and a statement or
block of statements. If the
expression is true then the
statement or block of statements
gets executed otherwise these
statements are skipped.
if statement (example)
/* Global variable definition */ int A = 5 ; int B= 9 ;
Void setup ()
{
}
Void loop () {
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/ A++;
/* check the boolean condition */
If ( ( A>B ) && ( B!=0 )) /* if condition is true then execute the following statement*/
{ A+=B;
B--;
}
}
If …else statement
/* Global variable definition */ int A = 5 ; int B= 9 ;
Void setup ()
{
}
Void loop ()
{
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/
{
A++; } else {
B -= A;
} }
if…else if …else statement
The if statement can be followed by an optional else
if...else statement, which is very useful to test various
conditions using single if...else if statement.
When using if...else if…else statements, keep in
mind −
•An if can have zero or one else statement and it must come
after any else if's.
•An if can have zero to many else if statements and they must
come before the else.
•Once an else if succeeds, none of the remaining else if or
else statements will be tested.
if…else if …else statement (example)
/* Global variable definition */ int A = 5 ; int B= 9 ; int c=15;
Void setup ()
{
}
Void loop ()
{
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/
{
A++;
}
/* check the boolean condition */
else if ((A==B )||( B < c) ) /* if condition is true then execute the following
statement*/
{
C =B* A;
} else c++;
}
Switch Case Statement
Similar to the if statements, switch...case controls
the flow of programs by allowing the programmers
to specify different codes that should be executed in
various conditions. In particular, a switch statement
compares the value of a variable to the values
specified in the case statements. When a case
statement is found whose value matches that of the
variable, the code in that case statement is run.
The break keyword makes the switch statement exit,
and is typically used at the end of each case. Without
a break statement, the switch statement will
continue executing the following expressions
("falling-through") until a break, or the end of the
switch statement is reached.
switch (variable)
{ case label: // statements break;
} case label:
{
// statements break; } default:
{
// statements break;
}
}
Switch Case Statement Syntax
switch (phase)
{
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default:
Message("Invalid
state!");
Here is a simple example with switch.
Suppose we have a variable phase
with only 3 different states (0, 1, or
2) and a corresponding function
(event) for each of these states. This
is how we could switch the code to
the appropriate routine:
Loops
Programming languages provide various
control structures that allow for more
complicated execution paths. A loop
statement allows us to execute a
statement or group of statements
multiple times and following is the general
form of a loop statement in most of the
programming languages –
C programming language provides the
following types of loops to handle looping
requirements.
• while loop
• do…while loop
• for loop
• nested loop
• infinite loop
while loop
while loops will loop continuously, and
infinitely, until the expression inside the
parenthesis, () becomes false. Something
must change the tested variable, or the
while loop will never exit.
do…while loop
The do…while loop is similar to the while
loop. In the while loop, the loop-
continuation condition is tested at the
beginning of the loop before performed
the body of the loop. The do…while
statement tests the loop-continuation
condition after performed the loop body.
Therefore, the loop body will be executed
at least once. When a do…while
terminates, execution continues with the
statement after the while clause. It is not
necessary to use braces in the do…while
statement if there is only one statement in
the body. However, the braces are usually
included to avoid confusion between the
while and do…while statements.
do{
Block of statements;
} while (expression);
for loop
A for loop executes statements a
predetermined number of times. The
control expression for the loop is
initialized, tested and manipulated entirely
within the for loop parentheses. It is easy
to debug the looping behavior of the
structure as it is independent of the activity
inside the loop.
Each for loop has up to three expressions,
which determine its operation. The
following example shows general for loop
syntax. Notice that the three expressions in
the for loop argument parentheses are
separated with semicolons.
for(counter=2;counter
<=9;counter++)
{
//statements block will
executed 10 times
}
Nested Loop
C language allows you to use one
loop inside another loop. The
following example illustrates the
concept.
for(counter=0;counter<=9;counter++)
{
//statements block will executed 10
times
for(i=0;i<=99;i++)
{
//statements block will executed 100
times
}
}
Functions
Functions allow structuring
the programs in segments of
code to perform individual
tasks. The typical case for
creating a function is when
one needs to perform the
same action multiple times
in a program.
Advantages:
•Functions help the programmer stay organized. Often
this helps to conceptualize the programdo…while loop
•Functions codify one action in one place so that the
function only has to be thought about and debugged
once.
•This also reduces chances for errors in modification, if
the code needs to be changed.
•Functions make the whole sketch smaller and more
compact because sections of code are reused many
times.
•They make it easier to reuse code in other programs by
making it modular, and using functions often makes the
code more readable.
There are two required
functions in an Arduino
sketch or a program i.e.
setup () and loop(). Other
functions must be created
outside the brackets of these
two functions.
The most common syntax to
define a function is:
Function Declaration
A function is declared outside
any other functions, above or
below the loop function.
We can declare the function in
two different ways -
Function Declaration
The first way is just writing the part of
the function called a function
prototype above the loop function,
which consists of:
•Function return type
•Function name
•Function argument type, no need to
write the argument name
Function prototype must be followed
by a semicolon ( ; )
int sum_func (int x, int y) // function declaration
{ int z=0; z= x+y ;
return z; // return the value
}
void setup ()
{
Statements // group of statements
}
Void loop ()
{
int result =0 ;
result = Sum_func (5,6) ; // function call
}
Function Declaration
The second part, which is called the
function definition or declaration,
must be declared below the loop
function, which consists of -
•Function return type
•Function name
•Function argument type, here you
must add the argument name
•The function body (statements inside
the function executing when the
function is called)
int sum_func (int , int ) ; // function prototype
void setup ()
{
Statements // group of statements
}
Void loop ()
{
int result =0 ;
result = Sum_func (5,6) ; // function call
}
int sum_func (int x, int y) // function
declaration
{ int z=0; z= x+y ;
return z; // return the value
}
Strings
Strings are used to store text. They
can be used to display text on an LCD
or in the Arduino IDE Serial Monitor
window. Strings are also useful for
storing the user input. For example,
the characters that a user types on a
keypad connected to the Arduino.
There are two types of strings in
Arduino programming:
•Arrays of characters, which are the
same as the strings used in C
programming.
•The Arduino String, which lets us
use a string object in a sketch.
String Character Arrays
The first type of string that we will learn
is the string that is a series of characters
of the type char.
we learned what an array is; a
consecutive series of the same type of
variable stored in memory. A string is an
array of char variables.
A string is a special array that has one
extra element at the end of the string,
which always has the value of 0 (zero).
This is known as a "null terminated
string".
void setup()
{
char my_str[6]; // an array big enough for a 5 character
string Serial.begin(9600);
my_str[0] = 'H'; // the string consists of 5 characters
my_str[1] = 'e'; my_str[2] = 'l'; my_str[3] = 'l'; my_str[4] =
'o';
my_str[5] = 0; // 6th array element is a null terminator
Serial.println(my_str);
}
void loop()
{ }
String Character Arrays
A string is made up of; a character
array with printable characters and 0
as the last element of the array to
show that this is where the string
ends. The string can be printed out to
the Arduino IDE Serial Monitor
window by using Serial.println() and
passing the name of the string.
void setup()
{
char my_str[] = "Hello"; Serial.begin(9600);
Serial.println(my_str);
}
void loop()
{
}
Manipulating String Arrays
void setup()
{
char like[] = "I like coffee and cake"; // create a string
Serial.begin(9600);
// (1) print the string
Serial.println(like);
// (2) delete part of the string
like[13] = 0;
Serial.println(like);
// (3) substitute a word into the string
like[13] = ' '; // replace the null terminator with a space
like[18] = 't'; // insert the new word like[19] = 'e'; like[20] = 'a';
like[21] = 0; // terminate the string
Serial.println(like);
} void loop()
{ }
Result
I like coffee and cake
I like coffee
I like coffee and tea
Functions to Manipulate String
Arrays
Functions Description
String() The String class, part of the core as of version 0019, allows you to use and manipulate strings of text in more
complex ways than character arrays do. You can concatenate Strings, append to them, search for and replace
substrings, and more. It takes more memory than a simple character array, but it is also more useful.
For reference, character arrays are referred to as strings with a small ‘s’, and instances of the String class are
referred to as Strings with a capital S. Note that constant strings, specified in
"double quotes" are treated as char arrays, not instances of the String class
charAt() Access a particular character of the String.
compareTo() Compares two Strings, testing whether one comes before or after the other, or whether they are equal. The strings
are compared character by character, using the ASCII values of the characters. That means, for example, 'a' comes
before 'b' but after 'A'. Numbers come before letters.
concat() Appends the parameter to a String.
c_str() Converts the contents of a string as a C-style, null-terminated string. Note that this gives direct access to the
internal String buffer and should be used with care. In particular, you should never modify the string through the
pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by
c_str() becomes invalid and should not be used any longer.
endsWith() Tests whether or not a String ends with the characters of another String.
equals() Compares two strings for equality. The comparison is casesensitive, meaning the String "hello" is not equal to the
String "HELLO".
Functions to Manipulate String
Arrays
equalsIgnoreCase() Compares two strings for equality. The comparison is not casesensitive, meaning the String("hello") is equal to
the String("HELLO").
getBytes() Copies the string's characters to the supplied buffer.
indexOf() Locates a character or String within another String. By default, it searches from the beginning of the String, but can
also start
from a given index, allowing to locate all instances of the character or String.
lastIndexOf() Locates a character or String within another String. By default, it searches from the end of the String, but can also
work backwards from a given index, allowing to locate all instances of the character or String.
length() Returns the length of the String, in characters. (Note that this does not include a trailing null character.)
remove() Modify in place, a string removing chars from the provided index to the end of the string or from the provided
index to index plus count.
replace() The String replace() function allows you to replace all instances of a given character with another character. You
can also use replace to replace substrings of a string with a different substring.
reserve() The String reserve() function allows you to allocate a buffer in memory for manipulating strings.
setCharAt() Sets a character of the String. Has no effect on indices outside the existing length of the String.
startsWith() Tests whether or not a String starts with the characters of another String.
toCharArray() Copies the string's characters to the supplied buffer.
substring() Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring),
but the optional ending index is exclusive (the corresponding character is not included in the substring). If the
ending index is omitted, the substring continues to the end of the String.
Functions to Manipulate String
Arrays
toInt() Converts a valid String to an integer. The input string should start with an integer number. If the string contains
non-integer numbers, the function will stop performing the conversion.
toFloat() Converts a valid String to a float. The input string should start with a digit. If the string contains non-digit
characters, the function will stop performing the conversion. For example, the strings "123.45", "123", and
"123fish" are converted to 123.45, 123.00, and 123.00 respectively. Note that "123.456" is approximated with
123.46. Note too that floats have only 6-7 decimal digits of precision and that longer strings might be truncated.
toLowerCase() Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the string in place rather than returning a
new.
toUpperCase() Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the string in place rather than returning a
new one.
trim() Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the string in
place rather than returning a new one.
Serial.print("Size of the array: ");
Serial.println(num);
// (4) copy a string strcpy(out_str, str);
Serial.println(out_str);
// (5) add a string to the end of a string (append) strcat(out_str, " sketch."); Serial.println(out_str); num =
strlen(out_str);
Serial.print("String length is: ");
Serial.println(num);
num = sizeof(out_str);
Serial.print("Size of the array out_str[]: ");
Serial.println(num);
} void loop()
{
}
void setup()
{
char str[] = "This is my string"; // create a string
char out_str[40]; // output from string functions placed here
int num; // general purpose integer
Serial.begin(9600);
// (1) print the string
Serial.println(str);
// (2) get the length of the string (excludes null terminator) num = strlen(str);
Serial.print("String length is: ");
Serial.println(num);
// (3) get the length of the array (includes null terminator) num = sizeof(str); // sizeof() is not a C string
function
The sketch works in the following way.
•Print the String
The newly created string is printed to the Serial Monitor window as done in previous sketches.
•Get the Length of the String
The strlen() function is used to get the length of the string. The length of the string is for the printable characters only and does not include
the null terminator.
The string contains 17 characters, so we see 17 printed in the Serial Monitor window.
•Get the Length of the Array
The operator sizeof() is used to get the length of the array that contains the string. The length includes the null terminator, so the length is
one more than the length of the string.
sizeof() looks like a function, but technically is an operator. It is not a part of the C string library, but was used in the sketch to show the
difference between the size of the array and the size of the string (or string length).
Copy a String
The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the second
string passed to it into the first string. A copy of the string now exists in the out_num[] array, but only takes up 18
elements of the array, so we still have 22 free char elements in the array. These free elements are found after the
string in memory.
The string was copied to the array so that we would have some extra space in the array to use in the next part of the
sketch, which is adding a string to the end of a string.
Append a String to a String (Concatenate)
The sketch joins one string to another, which is known as concatenation. This is done using the strcat() function. The
strcat() function puts the second string passed to it onto the end of the first string passed to it.
After concatenation, the length of the string is printed to show the new string length. The length of the array is then
printed to show that we have a 25-character long string in a 40 element long array.
Remember that the 25-character long string actually takes up 26 characters of the array because of the null
terminating zero.
Thank you
Niket Chandrawanshi
Contact: +91-7415045756
niket.chandrawanshi@outlook.com
To know more: http://www.niketchandrawanshi.me/

Mais conteúdo relacionado

Mais procurados

Introduction to Arduino Microcontroller
Introduction to Arduino MicrocontrollerIntroduction to Arduino Microcontroller
Introduction to Arduino MicrocontrollerMujahid Hussain
 
Arduino Microcontroller
Arduino MicrocontrollerArduino Microcontroller
Arduino MicrocontrollerShyam Mohan
 
Interfacing with peripherals: analog to digital converters and digital to ana...
Interfacing with peripherals: analog to digital converters and digital to ana...Interfacing with peripherals: analog to digital converters and digital to ana...
Interfacing with peripherals: analog to digital converters and digital to ana...NimeshSingh27
 
Internal architecture-of-8086
Internal architecture-of-8086Internal architecture-of-8086
Internal architecture-of-8086Estiak Khan
 
8051 Microcontroller I/O ports
8051 Microcontroller I/O ports8051 Microcontroller I/O ports
8051 Microcontroller I/O portsanishgoel
 
ARDUINO AND ITS PIN CONFIGURATION
 ARDUINO AND ITS PIN  CONFIGURATION ARDUINO AND ITS PIN  CONFIGURATION
ARDUINO AND ITS PIN CONFIGURATIONsoma saikiran
 
Presentation on 8086 Microprocessor
Presentation  on   8086 MicroprocessorPresentation  on   8086 Microprocessor
Presentation on 8086 MicroprocessorNahian Ahmed
 
Pic 18 microcontroller
Pic 18 microcontrollerPic 18 microcontroller
Pic 18 microcontrollerAshish Ranjan
 
Arduino Workshop Day 2 - Advance Arduino & DIY
Arduino Workshop Day 2 - Advance Arduino & DIYArduino Workshop Day 2 - Advance Arduino & DIY
Arduino Workshop Day 2 - Advance Arduino & DIYVishnu
 

Mais procurados (20)

8255 ppi
8255 ppi8255 ppi
8255 ppi
 
I/O Ports
I/O Ports I/O Ports
I/O Ports
 
8051 Timer
8051 Timer8051 Timer
8051 Timer
 
Arduino Functions
Arduino FunctionsArduino Functions
Arduino Functions
 
Introduction to Arduino Microcontroller
Introduction to Arduino MicrocontrollerIntroduction to Arduino Microcontroller
Introduction to Arduino Microcontroller
 
Arduino Microcontroller
Arduino MicrocontrollerArduino Microcontroller
Arduino Microcontroller
 
8051 io interface
8051 io interface8051 io interface
8051 io interface
 
Interfacing with peripherals: analog to digital converters and digital to ana...
Interfacing with peripherals: analog to digital converters and digital to ana...Interfacing with peripherals: analog to digital converters and digital to ana...
Interfacing with peripherals: analog to digital converters and digital to ana...
 
Arduino Uno Pin Description
Arduino Uno Pin DescriptionArduino Uno Pin Description
Arduino Uno Pin Description
 
Instruction types
Instruction typesInstruction types
Instruction types
 
Arduino- Serial communication
Arduino-  Serial communicationArduino-  Serial communication
Arduino- Serial communication
 
Internal architecture-of-8086
Internal architecture-of-8086Internal architecture-of-8086
Internal architecture-of-8086
 
8051 memory
8051 memory8051 memory
8051 memory
 
Arduino
ArduinoArduino
Arduino
 
8051 Microcontroller I/O ports
8051 Microcontroller I/O ports8051 Microcontroller I/O ports
8051 Microcontroller I/O ports
 
ARDUINO AND ITS PIN CONFIGURATION
 ARDUINO AND ITS PIN  CONFIGURATION ARDUINO AND ITS PIN  CONFIGURATION
ARDUINO AND ITS PIN CONFIGURATION
 
Intel 8051 Programming in C
Intel 8051 Programming in CIntel 8051 Programming in C
Intel 8051 Programming in C
 
Presentation on 8086 Microprocessor
Presentation  on   8086 MicroprocessorPresentation  on   8086 Microprocessor
Presentation on 8086 Microprocessor
 
Pic 18 microcontroller
Pic 18 microcontrollerPic 18 microcontroller
Pic 18 microcontroller
 
Arduino Workshop Day 2 - Advance Arduino & DIY
Arduino Workshop Day 2 - Advance Arduino & DIYArduino Workshop Day 2 - Advance Arduino & DIY
Arduino Workshop Day 2 - Advance Arduino & DIY
 

Semelhante a Programming in Arduino (Part 2)

Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Techglyphs
 
Control statements
Control statementsControl statements
Control statementsCutyChhaya
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxSKUP1
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxLECO9
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)Jyoti Bhardwaj
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYRajeshkumar Reddy
 
C++ decision making
C++ decision makingC++ decision making
C++ decision makingZohaib Ahmed
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguageTanmay Modi
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
Btech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsBtech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsRai University
 

Semelhante a Programming in Arduino (Part 2) (20)

Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
java notes.pdf
java notes.pdfjava notes.pdf
java notes.pdf
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Control statements
Control statementsControl statements
Control statements
 
Final requirement
Final requirementFinal requirement
Final requirement
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Loops
LoopsLoops
Loops
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Constructs (Programming Methodology)
Constructs (Programming Methodology)Constructs (Programming Methodology)
Constructs (Programming Methodology)
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
Loops c++
Loops c++Loops c++
Loops c++
 
Decision statements in c laguage
Decision statements in c laguageDecision statements in c laguage
Decision statements in c laguage
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Btech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsBtech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statements
 

Mais de Niket Chandrawanshi

Mais de Niket Chandrawanshi (9)

How MQTT work ?
How MQTT work ?How MQTT work ?
How MQTT work ?
 
Programming in Arduino (Part 1)
Programming in Arduino (Part 1)Programming in Arduino (Part 1)
Programming in Arduino (Part 1)
 
What is Arduino ?
What is Arduino ?What is Arduino ?
What is Arduino ?
 
37 things you should Do before Die !!!
37 things you should Do before Die !!!37 things you should Do before Die !!!
37 things you should Do before Die !!!
 
Microsoft student partners fy14 reruitment
Microsoft student partners fy14 reruitmentMicrosoft student partners fy14 reruitment
Microsoft student partners fy14 reruitment
 
Windows Azure Overview
Windows Azure OverviewWindows Azure Overview
Windows Azure Overview
 
Html5 Basic Structure
Html5 Basic StructureHtml5 Basic Structure
Html5 Basic Structure
 
TCP/IP
TCP/IPTCP/IP
TCP/IP
 
VLC Visible light communication (leaders of li fi)
VLC Visible light communication (leaders of li fi)VLC Visible light communication (leaders of li fi)
VLC Visible light communication (leaders of li fi)
 

Último

Call Girls In Munirka>༒9599632723 Incall_OutCall Available
Call Girls In Munirka>༒9599632723 Incall_OutCall AvailableCall Girls In Munirka>༒9599632723 Incall_OutCall Available
Call Girls In Munirka>༒9599632723 Incall_OutCall AvailableCall Girls in Delhi
 
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作f3774p8b
 
Dubai Call Girls O525547819 Spring Break Fast Call Girls Dubai
Dubai Call Girls O525547819 Spring Break Fast Call Girls DubaiDubai Call Girls O525547819 Spring Break Fast Call Girls Dubai
Dubai Call Girls O525547819 Spring Break Fast Call Girls Dubaikojalkojal131
 
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best ServicesVip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Servicesnajka9823
 
Computer Organization and Architecture 10th - William Stallings, Ch01.pdf
Computer Organization and Architecture 10th - William Stallings, Ch01.pdfComputer Organization and Architecture 10th - William Stallings, Ch01.pdf
Computer Organization and Architecture 10th - William Stallings, Ch01.pdfShahdAbdElsamea2
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...Amil Baba Dawood bangali
 
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...ttt fff
 
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作ss846v0c
 
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degreeyuu sss
 
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...Amil baba
 
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一diploma 1
 
澳洲Deakin学位证,迪肯大学毕业证书1:1制作
澳洲Deakin学位证,迪肯大学毕业证书1:1制作澳洲Deakin学位证,迪肯大学毕业证书1:1制作
澳洲Deakin学位证,迪肯大学毕业证书1:1制作rpb5qxou
 
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...Amil baba
 
existing product research b2 Sunderland Culture
existing product research b2 Sunderland Cultureexisting product research b2 Sunderland Culture
existing product research b2 Sunderland CultureChloeMeadows1
 
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...Amil Baba Dawood bangali
 
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)861c7ca49a02
 
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degreeyuu sss
 
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degreeyuu sss
 
RBS学位证,鹿特丹商学院毕业证书1:1制作
RBS学位证,鹿特丹商学院毕业证书1:1制作RBS学位证,鹿特丹商学院毕业证书1:1制作
RBS学位证,鹿特丹商学院毕业证书1:1制作f3774p8b
 

Último (20)

Call Girls In Munirka>༒9599632723 Incall_OutCall Available
Call Girls In Munirka>༒9599632723 Incall_OutCall AvailableCall Girls In Munirka>༒9599632723 Incall_OutCall Available
Call Girls In Munirka>༒9599632723 Incall_OutCall Available
 
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作
Erfurt FH学位证,埃尔福特应用技术大学毕业证书1:1制作
 
Dubai Call Girls O525547819 Spring Break Fast Call Girls Dubai
Dubai Call Girls O525547819 Spring Break Fast Call Girls DubaiDubai Call Girls O525547819 Spring Break Fast Call Girls Dubai
Dubai Call Girls O525547819 Spring Break Fast Call Girls Dubai
 
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best ServicesVip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Services
Vip Udupi Call Girls 7001305949 WhatsApp Number 24x7 Best Services
 
Computer Organization and Architecture 10th - William Stallings, Ch01.pdf
Computer Organization and Architecture 10th - William Stallings, Ch01.pdfComputer Organization and Architecture 10th - William Stallings, Ch01.pdf
Computer Organization and Architecture 10th - William Stallings, Ch01.pdf
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uk England Northern ...
 
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...
毕业文凭制作#回国入职#diploma#degree美国威斯康星大学麦迪逊分校毕业证成绩单pdf电子版制作修改#毕业文凭制作#回国入职#diploma#d...
 
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作
美国IUB学位证,印第安纳大学伯明顿分校毕业证书1:1制作
 
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
 
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...
Uae-NO1 Amil Baba In Karachi Kala Jadu In Karachi Amil baba In Karachi Addres...
 
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一
办理(CSU毕业证书)澳洲查理斯特大学毕业证成绩单原版一比一
 
澳洲Deakin学位证,迪肯大学毕业证书1:1制作
澳洲Deakin学位证,迪肯大学毕业证书1:1制作澳洲Deakin学位证,迪肯大学毕业证书1:1制作
澳洲Deakin学位证,迪肯大学毕业证书1:1制作
 
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...
NO1 Certified Vashikaran Specialist in Uk Black Magic Specialist in Uk Black ...
 
existing product research b2 Sunderland Culture
existing product research b2 Sunderland Cultureexisting product research b2 Sunderland Culture
existing product research b2 Sunderland Culture
 
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...
NO1 Certified Black Magic Specialist Expert In Bahawalpur, Sargodha, Sialkot,...
 
young call girls in Gtb Nagar,🔝 9953056974 🔝 escort Service
young call girls in Gtb Nagar,🔝 9953056974 🔝 escort Serviceyoung call girls in Gtb Nagar,🔝 9953056974 🔝 escort Service
young call girls in Gtb Nagar,🔝 9953056974 🔝 escort Service
 
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)
5S - House keeping (Seiri, Seiton, Seiso, Seiketsu, Shitsuke)
 
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
1:1原版定制美国加州州立大学东湾分校毕业证成绩单pdf电子版制作修改#真实留信入库#永久存档#真实可查#diploma#degree
 
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
专业一比一美国旧金山艺术学院毕业证成绩单pdf电子版制作修改#真实工艺展示#真实防伪#diploma#degree
 
RBS学位证,鹿特丹商学院毕业证书1:1制作
RBS学位证,鹿特丹商学院毕业证书1:1制作RBS学位证,鹿特丹商学院毕业证书1:1制作
RBS学位证,鹿特丹商学院毕业证书1:1制作
 

Programming in Arduino (Part 2)

  • 1. Programming in Arduino PART 2 BY: NIKET CHANDRAWANSHI HTTP://WWW.NIKETCHANDRAWANSHI.ME/
  • 2. Control Statements Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program. It should be along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. • If statement • If …else statement • If…else if …else statement • switch case statement • Conditional Operator ? :
  • 3. if statement It takes an expression in parenthesis and a statement or block of statements. If the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
  • 4. if statement (example) /* Global variable definition */ int A = 5 ; int B= 9 ; Void setup () { } Void loop () { /* check the boolean condition */ if (A > B) /* if condition is true then execute the following statement*/ A++; /* check the boolean condition */ If ( ( A>B ) && ( B!=0 )) /* if condition is true then execute the following statement*/ { A+=B; B--; } }
  • 5. If …else statement /* Global variable definition */ int A = 5 ; int B= 9 ; Void setup () { } Void loop () { /* check the boolean condition */ if (A > B) /* if condition is true then execute the following statement*/ { A++; } else { B -= A; } }
  • 6. if…else if …else statement The if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...else if statement. When using if...else if…else statements, keep in mind − •An if can have zero or one else statement and it must come after any else if's. •An if can have zero to many else if statements and they must come before the else. •Once an else if succeeds, none of the remaining else if or else statements will be tested.
  • 7. if…else if …else statement (example) /* Global variable definition */ int A = 5 ; int B= 9 ; int c=15; Void setup () { } Void loop () { /* check the boolean condition */ if (A > B) /* if condition is true then execute the following statement*/ { A++; } /* check the boolean condition */ else if ((A==B )||( B < c) ) /* if condition is true then execute the following statement*/ { C =B* A; } else c++; }
  • 8. Switch Case Statement Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run. The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached. switch (variable) { case label: // statements break; } case label: { // statements break; } default: { // statements break; } }
  • 9. Switch Case Statement Syntax switch (phase) { case 0: Lo(); break; case 1: Mid(); break; case 2: Hi(); break; default: Message("Invalid state!"); Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine:
  • 10. Loops Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages – C programming language provides the following types of loops to handle looping requirements. • while loop • do…while loop • for loop • nested loop • infinite loop
  • 11. while loop while loops will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit.
  • 12. do…while loop The do…while loop is similar to the while loop. In the while loop, the loop- continuation condition is tested at the beginning of the loop before performed the body of the loop. The do…while statement tests the loop-continuation condition after performed the loop body. Therefore, the loop body will be executed at least once. When a do…while terminates, execution continues with the statement after the while clause. It is not necessary to use braces in the do…while statement if there is only one statement in the body. However, the braces are usually included to avoid confusion between the while and do…while statements. do{ Block of statements; } while (expression);
  • 13. for loop A for loop executes statements a predetermined number of times. The control expression for the loop is initialized, tested and manipulated entirely within the for loop parentheses. It is easy to debug the looping behavior of the structure as it is independent of the activity inside the loop. Each for loop has up to three expressions, which determine its operation. The following example shows general for loop syntax. Notice that the three expressions in the for loop argument parentheses are separated with semicolons. for(counter=2;counter <=9;counter++) { //statements block will executed 10 times }
  • 14. Nested Loop C language allows you to use one loop inside another loop. The following example illustrates the concept. for(counter=0;counter<=9;counter++) { //statements block will executed 10 times for(i=0;i<=99;i++) { //statements block will executed 100 times } }
  • 15. Functions Functions allow structuring the programs in segments of code to perform individual tasks. The typical case for creating a function is when one needs to perform the same action multiple times in a program. Advantages: •Functions help the programmer stay organized. Often this helps to conceptualize the programdo…while loop •Functions codify one action in one place so that the function only has to be thought about and debugged once. •This also reduces chances for errors in modification, if the code needs to be changed. •Functions make the whole sketch smaller and more compact because sections of code are reused many times. •They make it easier to reuse code in other programs by making it modular, and using functions often makes the code more readable.
  • 16. There are two required functions in an Arduino sketch or a program i.e. setup () and loop(). Other functions must be created outside the brackets of these two functions. The most common syntax to define a function is:
  • 17. Function Declaration A function is declared outside any other functions, above or below the loop function. We can declare the function in two different ways -
  • 18. Function Declaration The first way is just writing the part of the function called a function prototype above the loop function, which consists of: •Function return type •Function name •Function argument type, no need to write the argument name Function prototype must be followed by a semicolon ( ; ) int sum_func (int x, int y) // function declaration { int z=0; z= x+y ; return z; // return the value } void setup () { Statements // group of statements } Void loop () { int result =0 ; result = Sum_func (5,6) ; // function call }
  • 19. Function Declaration The second part, which is called the function definition or declaration, must be declared below the loop function, which consists of - •Function return type •Function name •Function argument type, here you must add the argument name •The function body (statements inside the function executing when the function is called) int sum_func (int , int ) ; // function prototype void setup () { Statements // group of statements } Void loop () { int result =0 ; result = Sum_func (5,6) ; // function call } int sum_func (int x, int y) // function declaration { int z=0; z= x+y ; return z; // return the value }
  • 20. Strings Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial Monitor window. Strings are also useful for storing the user input. For example, the characters that a user types on a keypad connected to the Arduino. There are two types of strings in Arduino programming: •Arrays of characters, which are the same as the strings used in C programming. •The Arduino String, which lets us use a string object in a sketch.
  • 21. String Character Arrays The first type of string that we will learn is the string that is a series of characters of the type char. we learned what an array is; a consecutive series of the same type of variable stored in memory. A string is an array of char variables. A string is a special array that has one extra element at the end of the string, which always has the value of 0 (zero). This is known as a "null terminated string". void setup() { char my_str[6]; // an array big enough for a 5 character string Serial.begin(9600); my_str[0] = 'H'; // the string consists of 5 characters my_str[1] = 'e'; my_str[2] = 'l'; my_str[3] = 'l'; my_str[4] = 'o'; my_str[5] = 0; // 6th array element is a null terminator Serial.println(my_str); } void loop() { }
  • 22. String Character Arrays A string is made up of; a character array with printable characters and 0 as the last element of the array to show that this is where the string ends. The string can be printed out to the Arduino IDE Serial Monitor window by using Serial.println() and passing the name of the string. void setup() { char my_str[] = "Hello"; Serial.begin(9600); Serial.println(my_str); } void loop() { }
  • 23. Manipulating String Arrays void setup() { char like[] = "I like coffee and cake"; // create a string Serial.begin(9600); // (1) print the string Serial.println(like); // (2) delete part of the string like[13] = 0; Serial.println(like); // (3) substitute a word into the string like[13] = ' '; // replace the null terminator with a space like[18] = 't'; // insert the new word like[19] = 'e'; like[20] = 'a'; like[21] = 0; // terminate the string Serial.println(like); } void loop() { } Result I like coffee and cake I like coffee I like coffee and tea
  • 24. Functions to Manipulate String Arrays Functions Description String() The String class, part of the core as of version 0019, allows you to use and manipulate strings of text in more complex ways than character arrays do. You can concatenate Strings, append to them, search for and replace substrings, and more. It takes more memory than a simple character array, but it is also more useful. For reference, character arrays are referred to as strings with a small ‘s’, and instances of the String class are referred to as Strings with a capital S. Note that constant strings, specified in "double quotes" are treated as char arrays, not instances of the String class charAt() Access a particular character of the String. compareTo() Compares two Strings, testing whether one comes before or after the other, or whether they are equal. The strings are compared character by character, using the ASCII values of the characters. That means, for example, 'a' comes before 'b' but after 'A'. Numbers come before letters. concat() Appends the parameter to a String. c_str() Converts the contents of a string as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care. In particular, you should never modify the string through the pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by c_str() becomes invalid and should not be used any longer. endsWith() Tests whether or not a String ends with the characters of another String. equals() Compares two strings for equality. The comparison is casesensitive, meaning the String "hello" is not equal to the String "HELLO".
  • 25. Functions to Manipulate String Arrays equalsIgnoreCase() Compares two strings for equality. The comparison is not casesensitive, meaning the String("hello") is equal to the String("HELLO"). getBytes() Copies the string's characters to the supplied buffer. indexOf() Locates a character or String within another String. By default, it searches from the beginning of the String, but can also start from a given index, allowing to locate all instances of the character or String. lastIndexOf() Locates a character or String within another String. By default, it searches from the end of the String, but can also work backwards from a given index, allowing to locate all instances of the character or String. length() Returns the length of the String, in characters. (Note that this does not include a trailing null character.) remove() Modify in place, a string removing chars from the provided index to the end of the string or from the provided index to index plus count. replace() The String replace() function allows you to replace all instances of a given character with another character. You can also use replace to replace substrings of a string with a different substring. reserve() The String reserve() function allows you to allocate a buffer in memory for manipulating strings. setCharAt() Sets a character of the String. Has no effect on indices outside the existing length of the String. startsWith() Tests whether or not a String starts with the characters of another String. toCharArray() Copies the string's characters to the supplied buffer. substring() Get a substring of a String. The starting index is inclusive (the corresponding character is included in the substring), but the optional ending index is exclusive (the corresponding character is not included in the substring). If the ending index is omitted, the substring continues to the end of the String.
  • 26. Functions to Manipulate String Arrays toInt() Converts a valid String to an integer. The input string should start with an integer number. If the string contains non-integer numbers, the function will stop performing the conversion. toFloat() Converts a valid String to a float. The input string should start with a digit. If the string contains non-digit characters, the function will stop performing the conversion. For example, the strings "123.45", "123", and "123fish" are converted to 123.45, 123.00, and 123.00 respectively. Note that "123.456" is approximated with 123.46. Note too that floats have only 6-7 decimal digits of precision and that longer strings might be truncated. toLowerCase() Get a lower-case version of a String. As of 1.0, toLowerCase() modifies the string in place rather than returning a new. toUpperCase() Get an upper-case version of a String. As of 1.0, toUpperCase() modifies the string in place rather than returning a new one. trim() Get a version of the String with any leading and trailing whitespace removed. As of 1.0, trim() modifies the string in place rather than returning a new one.
  • 27. Serial.print("Size of the array: "); Serial.println(num); // (4) copy a string strcpy(out_str, str); Serial.println(out_str); // (5) add a string to the end of a string (append) strcat(out_str, " sketch."); Serial.println(out_str); num = strlen(out_str); Serial.print("String length is: "); Serial.println(num); num = sizeof(out_str); Serial.print("Size of the array out_str[]: "); Serial.println(num); } void loop() { } void setup() { char str[] = "This is my string"; // create a string char out_str[40]; // output from string functions placed here int num; // general purpose integer Serial.begin(9600); // (1) print the string Serial.println(str); // (2) get the length of the string (excludes null terminator) num = strlen(str); Serial.print("String length is: "); Serial.println(num); // (3) get the length of the array (includes null terminator) num = sizeof(str); // sizeof() is not a C string function
  • 28. The sketch works in the following way. •Print the String The newly created string is printed to the Serial Monitor window as done in previous sketches. •Get the Length of the String The strlen() function is used to get the length of the string. The length of the string is for the printable characters only and does not include the null terminator. The string contains 17 characters, so we see 17 printed in the Serial Monitor window. •Get the Length of the Array The operator sizeof() is used to get the length of the array that contains the string. The length includes the null terminator, so the length is one more than the length of the string. sizeof() looks like a function, but technically is an operator. It is not a part of the C string library, but was used in the sketch to show the difference between the size of the array and the size of the string (or string length).
  • 29. Copy a String The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the second string passed to it into the first string. A copy of the string now exists in the out_num[] array, but only takes up 18 elements of the array, so we still have 22 free char elements in the array. These free elements are found after the string in memory. The string was copied to the array so that we would have some extra space in the array to use in the next part of the sketch, which is adding a string to the end of a string. Append a String to a String (Concatenate) The sketch joins one string to another, which is known as concatenation. This is done using the strcat() function. The strcat() function puts the second string passed to it onto the end of the first string passed to it. After concatenation, the length of the string is printed to show the new string length. The length of the array is then printed to show that we have a 25-character long string in a 40 element long array. Remember that the 25-character long string actually takes up 26 characters of the array because of the null terminating zero.
  • 30. Thank you Niket Chandrawanshi Contact: +91-7415045756 niket.chandrawanshi@outlook.com To know more: http://www.niketchandrawanshi.me/

Notas do Editor

  1. Result This is my string String length is: 17 Size of the array: 18 This is my string This is my string sketch. String length is: 25