Arduino - Basic Programming
Arduino - Basic Programming
The following table provides all the data types that you will use
during Arduino programming.
void
The void keyword is used only in function declarations. It indicates
that the function is expected to return no information to the
function from which it was called.
Example
Void Loop ( ) {
// rest of the code
}
Boolean
A Boolean holds one of two values, true or false. Each Boolean
variable occupies one byte of memory.
Example
boolean val = false ; // declaration of variable with type boolean and initialize
it with false
boolean state = true ; // declaration of variable with type boolean and initialize
it with true
Char
A data type that takes up one byte of memory that stores a
character value. Character literals are written in single quotes like
this: 'A' and for multiple characters, strings use double quotes:
"ABC".
However, characters are stored as numbers. You can see the
specific encoding in the ASCII chart. This means that it is possible
to do arithmetic operations on characters, in which the ASCII value
of the character is used. For example, 'A' + 1 has the value 66,
since the ASCII value of the capital letter A is 65.
Example
Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with
character a
Char chr_c = 97 ;//declaration of variable with type char and initialize it with
character 97
unsigned char
Unsigned char is an unsigned data type that occupies one byte of
memory. The unsigned char data type encodes numbers from 0 to
255.
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and
initialize it with character y
byte
A byte stores an 8-bit unsigned number, from 0 to 255.
Example
byte m = 25 ;//declaration of variable with type byte and initialize it with 25
int
Integers are the primary data-type for number storage. int stores a
16-bit (2-byte) value. This yields a range of -32,768 to 32,767
(minimum value of -2^15 and a maximum value of (2^15) - 1).
The int size varies from board to board. On the Arduino Due, for
example, an int stores a 32-bit (4-byte) value. This yields a range
of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and
a maximum value of (2^31) - 1).
Example
int counter = 32 ;// declaration of variable with type int and initialize it with
32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way
that they store a 2 byte value. Instead of storing negative
numbers, however, they only store positive values, yielding a
useful range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte
(32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
Example
Unsigned int counter = 60 ; // declaration of variable with
type unsigned int and initialize it with 60
Word
On the Uno and other ATMEGA based boards, a word stores a 16-
bit unsigned number. On the Due and Zero, it stores a 32-bit
unsigned number.
Example
word w = 1000 ;//declaration of variable with type word and initialize it with 1000
Long
Long variables are extended size variables for number storage, and
store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.
Example
Long velocity = 102346 ;//declaration of variable with type Long and initialize it
with 102346
unsigned long
Unsigned long variables are extended size variables for number
storage and store 32 bits (4 bytes). Unlike standard longs,
unsigned longs will not store negative numbers, making their range
from 0 to 4,294,967,295 (2^32 - 1).
Example
Unsigned Long velocity = 101006 ;// declaration of variable with
type Unsigned Long and initialize it with 101006
short
A short is a 16-bit data-type. On all Arduinos (ATMega and ARM
based), a short stores a 16-bit (2-byte) value. This yields a range
of -32,768 to 32,767 (minimum value of -2^15 and a maximum
value of (2^15) - 1).
Example
short val = 13 ;//declaration of variable with type short and initialize it with 13
float
Data type for floating-point number is a number that has a decimal
point. Floating-point numbers are often used to approximate the
analog and continuous values because they have greater resolution
than integers.
double
On the Uno and other ATMEGA based boards, Double precision
floating-point number occupies four bytes. That is, the double
implementation is exactly the same as the float, with no gain in
precision. On the Arduino Due, doubles have 8-byte (64 bit)
precision.
Example
double num = 45.352 ;// declaration of variable with type double and initia
Arduino - Variables & Constants
Before we start explaining the variable types, a very important
subject we need to make sure, you fully understand is called
the variable scope.
Local Variables
Variables that are declared inside a function or block are local
variables. They can be used only by the statements that are inside
that function or block of code. Local variables are not known to
function outside their own. Following is the example using local
variables −
Void setup () {
Void
loop () {
int
x , y ;
int
= 0;
y
= 0; actual initialization
= 10;
Global Variables
Global variables are defined outside of all the functions, usually at
the top of the program. The global variables will hold their value
throughout the life-time of your program.
Int T , S ;
float
Void setup () {
Void
loop () {
int
x , y ;
int
x
= 0;
= 0; actual initialization
= 10;
}
Arduino - Operators
An operator is a symbol that tells the compiler to perform specific
mathematical or logical functions. C language is rich in built-in
operators and provides the following types of operators −
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
A + B will
addition + Adds two operands
give 30
A * B will
multiplication * Multiply both operands
give 200
B % A will
modulo % Modulus Operator and
give 0
remainder of after an
integer division
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Show Example
(A & B) will
Binary AND Operator
give 12
and & copies a bit to the result if
which is
it exists in both operands.
0000 1100
(A | B) will
Binary OR Operator copies
give 61
or | a bit if it exists in either
which is
operand
0011 1101
(A ^ B) will
Binary XOR Operator
give 49
xor ^ copies the bit if it is set in
which is
one operand but not both.
0011 0001
(~A ) will
Binary Ones Complement
give -60
not ~ Operator is unary and has
which is
the effect of 'flipping' bits.
1100 0011
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Increment operator,
A++ will
increment ++ increases integer value
give 11
by one
Decrement operator,
A-- will give
decrement -- decreases integer value
9
by one
Subtract AND
assignment operator. It
B -= A is
compound subtracts right operand
-= equivalent
subtraction from the left operand
to B = B - A
and assign the result to
left operand
Multiply AND
assignment operator. It
B*= A is
compound multiplies right
*= equivalent
multiplication operand with the left
to B = B* A
operand and assign the
result to left operand
Modulus AND
assignment operator. It B %= A is
compound takes modulus using equivalent
%=
modulo two operands and to B = B %
assign the result to left A
operand
bitwise inclusive OR A |= 2 is
compound
|= and assignment same as A =
bitwise or
operator A|2
A &= 2 is
compound Bitwise AND
&= same as A =
bitwise and assignment operator
A&2
Arduino - 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
Conditional Operator ? :
while loop
do…while loop
for loop
Nested Loop
Infinite 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.
The first way is just writing the part of the function called a
function prototype above the loop function, which consists of −
Function name
Example
int sum_func (int x, int y) // function declaration {
int
z = 0;
z
= x+y ;
return
void
setup () {
Statements
// group of statements
Void
loop () {
int
result = 0 ;
result
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
int
int
z = 0;
= x+y ;
return
}
The second method just declares the function above the loop
function.
Arduino - 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.
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.
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".
Example
void setup() {
char
Serial
.begin(9600);
my_str
[1] = 'e';
my_str
[2] = 'l';
my_str
[3] = 'l';
my_str
[4] = 'o';
my_str
Serial
.println(my_str);
void
loop() {
Example
void setup() {
char
my_str[] = "Hello";
Serial
.begin(9600);
Serial
.println(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.
Example
void setup() {
char
Serial
.begin(9600);
Serial
.println(like);
like
[13] = 0;
Serial
.println(like);
like
like
like
[19] = 'e';
like
[20] = 'a';
like
Serial
.println(like);
void
loop() {
}
Result
I like coffee and cake
I like coffee
I like coffee and tea
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.
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.
Example
void setup() {
char
char
int
Serial
.begin(9600);
Serial
.println(str);
num
= strlen(str);
Serial
Serial
.println(num);
Serial
Serial
.println(num);
strcpy
(out_str, str);
Serial
.println(out_str);
strcat
Serial
.println(out_str);
num
= strlen(out_str);
Serial
Serial
.println(num);
num
= sizeof(out_str);
Serial
.println(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
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.
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.
Arduino - String Object
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.
Example
void setup() {
String
Serial
.begin(9600);
Serial
.println(my_str);
my_str
.toUpperCase();
Serial
.println(my_str);
// (3) overwrite the string
my_str
Serial
.println(my_str);
my_str
Serial
.println(my_str);
Serial
Serial
.println(my_str.length());
void
loop() {
Result
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22
This creates a String object with the name my_str and gives it a
value of "This is my string.".
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." ;
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.
delay () function
delayMicroseconds () function
millis () function
micros () function
Let us examine array C in the given figure, more closely. The name
of the entire array is C. Its 11 elements are referred to as C[0] to
C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of
C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78.
To print the sum of the values contained in the first three elements
of array C, we would write −
Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] );
Declaring Arrays
Arrays occupy space in memory. To specify the type of the
elements and the number of elements required by an array, use a
declaration of the form −
type arrayName [ arraySize ] ;
Example
void
setup () {
void
loop () {
for
Serial
.print (i) ;
Serial
.print (‘\r’) ;
for
.print (n[j]) ;
Serial
.print (‘\r’) ;
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
Example
// n is an array of 10 integers
int
void
setup () {
void
loop () {
for
Serial
.print (i) ;
Serial
.print (‘\r’) ;
for
Serial
.print (n[j]) ;
Serial
.print (‘\r’) ;
}
Result − It will produce the following result −
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Example
int
a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int
total = 0;
void
setup () {
}
void
loop () {
for
total
+= a[ i ];
Serial
Serial
.print(total) ;
2 Multi-Dimensional Arrays