0% found this document useful (0 votes)
5 views33 pages

Ch8 Arduino Tutorialspoint

The document provides an overview of control statements in Arduino programming, including decision-making structures such as if, if-else, and switch-case statements, as well as looping structures like while, do-while, and for loops. It also covers the concept of functions, their declarations, and the use of strings in Arduino sketches. The document emphasizes the importance of these programming constructs for controlling program flow and organizing code effectively.

Uploaded by

Noime 527
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

Ch8 Arduino Tutorialspoint

The document provides an overview of control statements in Arduino programming, including decision-making structures such as if, if-else, and switch-case statements, as well as looping structures like while, do-while, and for loops. It also covers the concept of functions, their declarations, and the use of strings in Arduino sketches. The document emphasizes the importance of these programming constructs for controlling program flow and organizing code effectively.

Uploaded by

Noime 527
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arduino – Control Statements Arduino

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.

Following is the general form of a typical decision making structure found in most of the
programming languages –

Control Statements are elements in Source Code that control the flow of program
execution. They are:

 If statement
 If …else statement
 If…else if …else statement
 switch case statement
 Conditional Operator ? :

33
Arduino

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.

Different forms of if statement


Form 1

if (expression)
statement;

You can use the if statement without braces { } if you have one statement.

Form 2

if (expression)
{
Block of statements;
}

if Statement – Execution Sequence

34
Arduino

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
An if statement can be followed by an optional else statement, which executes when the
expression is false.

if … else Statement Syntax


if (expression)
{
Block of statements;
}
else
{
Block of statements;
}

35
Arduino

if…else Statement – Execution Sequence

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++;
}
else
{
B -= A;
}
}

36
Arduino

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 Statements Syntax


if (expression_1)
{
Block of statements;
}
else if(expression_2)
{
Block of statements;
}
.
.
.
else
{
Block of statements;
}

37
Arduino

if … else if … else Statement Execution Sequence

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*/

38
Arduino

{
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 Case Statement Syntax


switch (variable)
{
case label:
// statements
break;
}
case label:
{
// statements
break;
}
default:
{
// statements
break;

39
Arduino

}
}

Switch Case Statement Execution Sequence

Example
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:

switch (phase)
{
case 0: Lo(); break;
case 1: Mid(); break;
case 2: Hi(); break;
default: Message("Invalid state!");

40
Arduino

Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C.

? : conditional operator Syntax


expression1 ? expression2 : expression3

Expression1 is evaluated first. If its value is true, then expression2 is evaluated and
expression3 is ignored. If expression1 is evaluated as false, then expression3 evaluates
and expression2 is ignored. The result will be a value of either expression2 or expression3
depending upon which of them evaluates as True.

Conditional operator associates from right to left.

Example
/* Find max(a, b): */
max = ( a > b ) ? a : b;
/* Convert small letter to capital: */
/* (no parentheses are actually necessary) */
c = ( c >= 'a' && c <= 'z' ) ? ( c - 32 ) : c;

Rules of Conditional Operator


 expression1 must be a scalar expression; expression2 and expression3 must obey
one of the following rules:

 Both expressions have to be of arithmetic type.

 expression2 and expression3 are subjected to usual arithmetic conversions, which


determines the resulting type.

Both expressions have to be of void type. The resulting type is void.

41
Arduino – Loops Arduino

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.

42
Arduino

while loop Syntax


while(expression)
{
Block of statements;
}

while loop Execution Sequence

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…while loop Syntax


do{
Block of statements;
} while (expression);

43
Arduino

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 loop Syntax


for ( initialize; control; increment or decrement)
{
// statement block
}

Example

for(counter=2;counter <=9;counter++)
{
//statements block will executed 10 times
}

for loop Execution Sequence

44
Arduino

Nested Loop
C language allows you to use one loop inside another loop. The following example
illustrates the concept.

nested loop Syntax


for ( initialize ;control; increment or decrement)
{
// statement block
for ( initialize ;control; increment or decrement)
{
// statement block
}
}

Example

for(counter=0;counter<=9;counter++)
{
//statements block will executed 10 times
for(i=0;i<=99;i++)
{
//statements block will executed 100 times
}
}

Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.

infinite loop Syntax


1. Using for loop

for (;;)
{
// statement block
}

45
Arduino

2. Using while loop

while(1)
{
// statement block
}

3. Using do…while loop

do{
Block of statements;
} while(1);

46
Arduino - Functions Arduino

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.

Standardizing code fragments into functions has several advantages:

 Functions help the programmer stay organized. Often this helps to conceptualize
the program.

 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:

47
Arduino

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 -

1. 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 ( ; ).

The following example shows the demonstration of the function declaration using the first
method.

Example
int sum_func (int x, int y) // function declaration
{
int z=0;
z= x+y ;
return z; // return the value
}
void setup ()

48
Arduino

{
Statements // group of statements
}
Void loop ()
{
int result =0 ;
result = Sum_func (5,6) ; // function call
}

2. 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)

The following example demonstrates the declaration of function using the second method.

Example
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
}

49
Arduino

The second method just declares the function above the loop function.

50
Arduino – Strings Arduino

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.

In this chapter, we will learn Strings, objects and the use of strings in Arduino sketches.
By the end of the chapter, you will learn which type of string to use 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. In the previous chapter, 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".

String Character Array Example


This example will show how to make a string and print it to the serial monitor window.

Example

void setup()
{
char my_str[6]; // an array big enough for a 5 character string
[Link](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
[Link](my_str);
}
void loop()
{ }

51
Arduino

The following example shows what 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
[Link]() and passing the name of the string.

This same example can be written in a more convenient way as shown below:

Example

void setup()
{
char my_str[] = "Hello";
[Link](9600);
[Link](my_str);
}
void loop()
{
}

In this sketch, the compiler calculates the size of the string array and also automatically
null terminates the string with a zero. An array that is six elements long and consists of
five characters followed by a zero is created exactly the same way as in the previous
sketch.

Manipulating String Arrays


We can alter a string array within a sketch as shown in the following sketch.

Example
void setup()
{
char like[] = "I like coffee and cake"; // create a string
[Link](9600);

// (1) print the string


[Link](like);

// (2) delete part of the string


like[13] = 0;
[Link](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';

52
Arduino

like[21] = 0; // terminate the string


[Link](like);
}
void loop()
{
}

Result
I like coffee and cake
I like coffee
I like coffee and tea

The sketch works in the following way.

(1) Creating and Printing the String


In the sketch given above, a new string is created and then printed for display in the Serial
Monitor window.

(2) Shortening the String


The string is shortened by replacing the 14th character in the string with a null terminating
zero (2). This is element number 13 in the string array counting from 0.

When the string is printed, all the characters are printed up to the new null terminating
zero. The other characters do not disappear; they still exist in the memory and the string
array is still the same size. The only difference is that any function that works with strings
will only see the string up to the first null terminator.

(3) Changing a Word in the String


Finally, the sketch replaces the word "cake" with "tea" (3). It first has to replace the null
terminator at like[13] with a space so that the string is restored to the originally created
format.

New characters overwrite "cak" of the word "cake" with the word "tea". This is done by
overwriting individual characters. The 'e' of "cake" is replaced with a new null terminating
character. The result is that the string is actually terminated with two null characters, the
original one at the end of the string and the new one that replaces the 'e' in "cake". This
makes no difference when the new string is printed because the function that prints the
string stops printing the string characters when it encounters the first null terminator.

53
Arduino

Functions to Manipulate String Arrays


The previous sketch manipulated the string in a manual way by accessing individual
characters in the string. To make it easier to manipulate string arrays, you can write your
own functions to do so, or use some of the string functions from the C language library.

Functions Description

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
String() 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.

Compares two Strings, testing whether one comes before or


after the other, or whether they are equal. The strings are
compareTo() 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.

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
c_str() 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.

Tests whether or not a String ends with the characters of


endsWith()
another String.

Compares two strings for equality. The comparison is case-


equals() sensitive, meaning the String "hello" is not equal to the String
"HELLO".

Compares two strings for equality. The comparison is not case-


equalsIgnoreCase() sensitive, 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

54
Arduino

from a given index, allowing to locate all instances of the


character or String.

Locates a character or String within another String. By default,


it searches from the end of the String, but can also work
lastIndexOf()
backwards from a given index, allowing to locate all instances
of the character or String.

Returns the length of the String, in characters. (Note that this


length()
does not include a trailing null character.)

Modify in place, a string removing chars from the provided


remove() index to the end of the string or from the provided index to
index plus count.

The String replace() function allows you to replace all instances


of a given character with another character. You can also use
replace()
replace to replace substrings of a string with a different
substring.

The String reserve() function allows you to allocate a buffer in


reserve()
memory for manipulating strings.

Sets a character of the String. Has no effect on indices outside


setCharAt()
the existing length of the String.

Tests whether or not a String starts with the characters of


startsWith()
another String.

toCharArray() Copies the string's characters to the supplied buffer.

Get a substring of a String. The starting index is inclusive (the


corresponding character is included in the substring), but the
substring() 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.

Converts a valid String to an integer. The input string should


toInt() start with an integer number. If the string contains non-integer
numbers, the function will stop performing the conversion.

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,
toFloat()
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.

Get a lower-case version of a String. As of 1.0, toLowerCase()


toLowerCase()
modifies the string in place rather than returning a new.

Get an upper-case version of a String. As of 1.0, toUpperCase()


toUpperCase()
modifies the string in place rather than returning a new one.

55
Arduino

Get a version of the String with any leading and trailing


trim() whitespace removed. As of 1.0, trim() modifies the string in
place rather than returning a new one.

The next sketch uses some C string functions.

Example
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
[Link](9600);

// (1) print the string


[Link](str);

// (2) get the length of the string (excludes null terminator)


num = strlen(str);
[Link]("String length is: ");
[Link](num);

// (3) get the length of the array (includes null terminator)


num = sizeof(str); // sizeof() is not a C string function
[Link]("Size of the array: ");
[Link](num);

// (4) copy a string


strcpy(out_str, str);
[Link](out_str);

// (5) add a string to the end of a string (append)


strcat(out_str, " sketch.");
[Link](out_str);
num = strlen(out_str);
[Link]("String length is: ");
[Link](num);

56
Arduino

num = sizeof(out_str);
[Link]("Size of the array out_str[]: ");
[Link](num);
}
void loop()
{
}

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
Size of the array out_str[]: 40

The sketch works in the following way.

(1) Print the String


The newly created string is printed to the Serial Monitor window as done in previous
sketches.

(2) 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.

(3) 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).

(4) 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

57
Arduino

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.

(5) 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.

Array Bounds
When working with strings and arrays, it is very important to work within the bounds of
strings or arrays. In the example sketch, an array was created, which was 40 characters
long, in order to allocate the memory that could be used to manipulate strings.

If the array was made too small and we tried to copy a string that is bigger than the array
to it, the string would be copied over the end of the array. The memory beyond the end
of the array could contain other important data used in the sketch, which would then be
overwritten by our string. If the memory beyond the end of the string is overrun, it could
crash the sketch or cause unexpected behavior.

58
Arduino – String Object Arduino

The second type of string used in Arduino programming is the String Object.

What is an Object?
An object is a construct that contains both data and functions. A String object can be
created just like a variable and assigned a value or string. The String object contains
functions (which are called "methods" in object oriented programming (OOP)) which
operate on the string data contained in the String object.

The following sketch and explanation will make it clear what an object is and how the
String object is used.

Example
void setup()
{ String my_str = "This is my string.";
[Link](9600);
// (1) print the string
[Link](my_str);
// (2) change the string to upper-case
my_str.toUpperCase();
[Link](my_str);
// (3) overwrite the string
my_str = "My new string.";
[Link](my_str);
// (4) replace a word in the string
my_str.replace("string", "Arduino sketch");
[Link](my_str);
// (5) get the length of the string
[Link]("String length is: ");
[Link](my_str.length());
}
void loop()
{ }

59
Arduino

Result
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22

A string object is created and assigned a value (or string) at the top of the sketch.

String my_str = "This is my string." ;

This creates a String object with the name my_str and gives it a value of "This is my
string.".

This can be compared to creating a variable and assigning a value to it such as an integer:

int my_var = 102;

The sketch works in the following way.

(1) Printing the String


The string can be printed to the Serial Monitor window just like a character array string.

(2) Convert the String to Upper-case


The string object my_str that was created, has a number of functions or methods that can
be operated on it. These methods are invoked by using the objects name followed by the
dot operator (.) and then the name of the function to use.

my_str.toUpperCase();

The toUpperCase() function operates on the string contained in the my_str object which
is of type String and converts the string data (or text) that the object contains to upper-
case characters. A list of the functions that the String class contains can be found in the
Arduino String reference. Technically, String is called a class and is used to create String
objects.

(3) Overwrite a String


The assignment operator is used to assign a new string to the my_str object that replaces
the old string.

my_str = "My new string." ;

The assignment operator cannot be used on character array strings, but works on String
objects only.

60
Arduino

(4) Replacing a Word in the String


The replace() function is used to replace the first string passed to it by the second string
passed to it. replace() is another function that is built into the String class and so is
available to use on the String object my_str.

(5) Getting the Length of the String


Getting the length of the string is easily done by using length(). In the example sketch,
the result returned by length() is passed directly to [Link]() without using an
intermediate variable.

When to Use a String Object


A String object is much easier to use than a string character array. The object has built-
in functions that can perform a number of operations on strings.

The main disadvantage of using the String object is that it uses a lot of memory and can
quickly use up the Arduinos RAM memory, which may cause Arduino to hang, crash or
behave unexpectedly. If a sketch on an Arduino is small and limits the use of objects, then
there should be no problems.

Character array strings are more difficult to use and you may need to write your own
functions to operate on these types of strings. The advantage is that you have control on
the size of the string arrays that you make, so you can keep the arrays small to save
memory.

You need to make sure that you do not write beyond the end of the array bounds with
string arrays. The String object does not have this problem and will take care of the string
bounds for you, provided there is enough memory for it to operate on. The String object
can try to write to memory that does not exist when it runs out of memory, but will never
write over the end of the string that it is operating on.

Where Strings are Used


In this chapter we studied about the strings, how they behave in memory and their
operations.

The practical uses of strings will be covered in the next part of this course when we study
how to get user input from the Serial Monitor window and save the input in a string.

61
Arduino – Time Arduino

Arduino provides four different time manipulation functions. They are-

 delay () function
 delayMicroseconds () function
 millis () function
 micros () function

delay() function
The way the delay() function works is pretty simple. It accepts a single integer (or
number) argument. This number represents the time (measured in milliseconds). The
program should wait until moving on to the next line of code when it encounters this
function. However, the problem is, the delay() function is not a good way to make your
program wait, because it is known as a “blocking” function.

delay() function Syntax


delay (ms) ;

where, ms is the time in milliseconds to pause (unsigned long).

Example

/* Flashing LED
* ------------
* Turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 2 seconds. *
*/
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second

62
Arduino

delayMicroseconds() function
The delayMicroseconds() function accepts a single integer (or number) argument. This
number represents the time and is measured in microseconds. There are a thousand
microseconds in a millisecond, and a million microseconds in a second.

Currently, the largest value that can produce an accurate delay is 16383. This may change
in future Arduino releases. For delays longer than a few thousand microseconds, you
should use the delay() function instead.

delay() function Syntax


delayMicroseconds (us) ;

where, us is the number of microseconds to pause (unsigned int)

Example

/* Flashing LED
* ------------
* Turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 1 seconds. *
*/
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delayMicroseconds(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delayMicroseconds(1000); // waits for a second
}

millis() function
This function is used to return the number of milliseconds at the time, the Arduino board
begins running the current program. This number overflows i.e. goes back to zero after
approximately 50 days.

63
Arduino

millis() function Syntax


millis () ;

This function returns milliseconds from the start of the program.

Example

unsigned long time;

void setup(){
[Link](9600);
}
void loop()
{
[Link]("Time:");
time = millis();
//prints time since program started
[Link](time);
// wait a second so as not to send massive amounts of data
delay(1000);
}

micros() function
The micros() function returns the number of microseconds from the time, the Arduino
board begins running the current program. This number overflows i.e. goes back to zero
after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano),
this function has a resolution of four microseconds (i.e. the value returned is always a
multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution
of eight microseconds.

micros() function Syntax


micros () ;

This function returns number of microseconds since the program started (unsigned long)

Example

unsigned long time;

void setup(){
[Link](9600);
}
void loop(){
[Link]("Time:");
time = micros();
//prints time since program started

64
Arduino

[Link](time);
// wait a second so as not to send massive amounts of data
delay(1000);
}

65

You might also like