You are on page 1of 8

Arduino

and C Programming Guide


1. Data types in C
In programming, a variable is a container used to store data. The variable is given a name, which can
then be used to reference and/or modify the actual data stored within the variable. For instance, in the
example below, the name of the variable is first_value and the data stored within the variable is 5.

first_value = 5;

When a program executes, it can use the variables as symbolic representations of the data that is stored
inside to perform arithmetic operations. In the example below, first_value has a value of 5, and
second_value has a value of 10. When these two values are added together, the variable total is
assigned to have a value of 5 + 10 = 15.

first_value = 5;
second_value = 10;
total = first_value + second_value;

Variables in C also have another important characteristic, their type. The type of the variable is used to
define what type of data is stored within the variable, so that it can be properly referenced when used in
the program execution. C has the following common variable datatypes:

int: int is used to define integer numbers. Integer numbers include all natural numbers (0, 1, 2,
3, ) together with the negatives of the non-zero natural numbers (-1, -2, -3, ). As such, the
only numbers that can be stored as ints are whole numbers.
float: float is used to define floating point numbers, that is, a number that has a decimal point
that can move, or float around within the number. Examples of floats include: 3.14125, 7.5,
0.99, etc.
char: char is used to store a character value, such as A or t. Characters are actually stored as
numbers however, with each character assigned a specific number according to the ASCII chart.
This means that it is possible to do arithmetic on characters, in which the ASCII value of the
character is used. Numbers can also be stored as text characters as well.
double: A double is short for a double precision floating point number, meaning that it is the
same as a float, but it allocates twice the amount of storage for use (or simply, a number with
twice as many bits can be stored). The amount of storage space will be discussed in more detail
below in section 2.1.
long: A long is the same to int as a double is to float. It has twice the storage space of an int so
that larger numbers (more bits) can be stored.
Boolean: A Boolean is a logic datatype that can represent one of two values. True (1) or False
(0). This datatype is used for logical comparisons and Boolean algebra.

When variables are used in C, they are initialized as one of the above types, and can only store data of
that specific type. In addition operations can only be done explicitly between variables of the same type

(adding ints to ints, multiplying floats by floats, etc.). For operations that require input from two
different data types, please see section 2.1.1 for information on typecasting and truncation.

1.1 Storage and Datatype conversion


Variables are assigned a type when they are declared to determine the amount of storage that they are
allotted, which is in turn related to how they are used within the program. In this way, the storage space
can be used more effectively since there will be a different amount of memory used for storing a single
character than there will to store a very large number (They will also be used differently within the
program as well).
The basic building block of memory within a computer or microprocessor is the bit. A bit is a single
binary value, either a 0 or a 1. Putting an ordered sequence of bits together allows larger numbers to be
stored in memory. Since binary is a base 2 numbering system, the number of values that can be
represented by a certain number of bits is given by 2number of bits 2!!"#$% !" !"#$ . For example, if you had a
5 bit number, then you could store 25 2! = 32 different values, or stated differently, a number from 0 to
31. Converting between a binary (base 2) and decimal (base 10) number and vice versa is relatively
simple. To convert from a binary number to decimal, simply write the powers of two from the right to
the left spaced evenly with each binary digit. Then simply add all of the powers up corresponding to 1s
in the binary number, ignoring those corresponding with 0s. An example is given below to convert the
binary number 10110101 to decimal.
1

2!

From the example above, the binary number 10110101 corresponds to the decimal number 2! + 0 +
2! + 2! + 0 + 2! + 0 + 2! = 128 + 0 + 32 + 16 + 0 + 4 + 0 + 1 = . In order to convert from a
decimal number to binary, simply do this process in reverse. Start with the highest power of two that is
still less than that number, and then add the decreasing powers of two until the number is reached. For
example, to represent the number 215 in binary, find the highest power of 2 that is still less than this
number, which is 2! = 128. Then check if adding 2! = 64 will go over 215 (it will not, so add it on).
Continue this process for 2! , 2! ,etc. until you have gone all the way through 2! . You will get 2! + 2! +
0 + 2! + 0 + 2! + 2! + 2! = 128 + 64 + 16 + 4 + 2 + 1 = . Once you have done this, write a 1
for each position that there was a power of two, and a zero for all the other positions to get the binary
number 11010111.
In a microcontroller such as the Arduino (as well as in computers), memory is organized using bytes. A
byte is an ordered collection of 8 bits which means that a single byte can store a number from 0 to 255.
(2! = 256 different values). The storage space of different variable types are represented using bytes
and are given below. For integers, you may notice that since the scope includes negative numbers, there
should be twice as much storage to hold the full range. In memory however, negative numbers are
stored using a sign bit and 2s complement math, something that is beyond the scope of this class other
than you knowing that it exists.

Int: 2 bytes = -32,768 to 32,767

Float: 4 bytes = -3.4028235E+38 to 3.4028235E+38 Note: Due to the way that floats are stored
(using an exponent and fraction), they can represent much higher numbers than just 2!"
although they have slightly lower precision.
Char: 1 byte = -128 to 127. Characters are encoded as numbers according to this ASCII Chart.
Note: Negative values are not used in the ASCII Chart, only the positive range.
Double: 4 bytes = Same as float. Note: Usually the Double variable occupies twice as much
memory as a float and has twice the precision. On the Arduino platform however, a double is
treated exactly the same as a float.
Long: 4 bytes = -2,147,483,648 to 2,147,483,647 (twice as many bits as an int)
Boolean: 1 byte = true notated by a 1 or false notated by a 0.

An important part of the way that values are stored in memory is what happens when a number that is
too large to be represented with the available storage space. This is called an overflow and is something
that must always be addressed in the programs that you write. An overflow can easily happen when two
large numbers are added together or a loop index is allowed to increase without bounds. When an
unsigned integer overflows, it results in undefined behavior, while a signed integer will rollover and
change signs (very large positive number becomes a very large negative number). The best way to
mitigate rollover is to plan out your code ahead of time and then declare the variables accordingly,
allocating enough memory for all operations to be performed. This will greatly reduce the time spent
debugging when your program does not behave as you would expect.

1.2 Typecasting and Truncation


Sometimes within a program it is useful to be able to convert a variable from one type to another in
order to use it in a certain operation. This can be accomplished by typecasting which treats the variable
like another type for a single operation (single line of code). The syntax to cast an int to a float and a
char to an int is given below.

example_float_variable = (float) example_int_variable;
example_int_variable = (int)example_char_variable;

This can be useful if you want to add the values of two different data types such as an int to a float:

int a = 5;
float b = 5.8;
int final_value = 0;

final_value = a + (int)b;

In the code above, the variables a, b, and final_value are all declared and initialized, then b is cast as an
int, added to a, and stored in the final_value variable. This brings up an important notion in typecasting
which is truncation. When a float is cast as an int, it can no longer store any fractional portion of the
float, and the fractional part is therefore dropped. In this way, if the value of the float is 5.95, when it is
typecast to an int, the .95 is dropped and the value is given as simply 5. This is an important concept to
remember, as it is simple to forget and assume that it just rounds the number.

Truncation is also an important concept to remember even when not typecasting variables. In integer
math, if the result of the operation has a fractional part, the fraction will be dropped which can cause
unexpected behavior in your program. For example, the code below shows integer division:

int a = 3;
int b = 5;
int c = result;

result = a/b;

The final value of result will be 0 since 3/5 = 0.6 which will be truncated to 0. Proper care should always
be taken in order to properly address situations where truncation will affect your programs behavior.

1.3 Declaration of Variables


At the beginning of the program, every variable used in the program is declared to the compiler. This
initial declaration serves two purposes:
1. It establishes the name of the variable, which is static for the remainder of the program
2. It establishes the type of the variable, that is, the type of data that the variable will hold
In addition, the declaration can be used to store an initial value within the variable. An example of a
simple variable declaration is included below. In this example, the variable a is declared as an int, and
is given an initial value of 0. The variable b is declared as a float, and given an initial value of 5.5, and
the variable c is declared as a char, and given an initial value of A

int a = 0;
float b = 5.5;
char c = A;

It is very important to initialize the variable to an initial value during the declaration. If you declare a
variable and do not initialize it, then the first time that the program references that variable, it will take
whatever value happens to be in the memory at that location. This can cause the program to have
unknown behavior and is a difficult error to catch when debugging.

2. Arithmetic Operators in C
Arithmetic Operators in C are used to perform arithmetic operations involving the calculation of
numerical values represented by variables. These operators include:

= (assignment):
Used to store the value to the right of the equals sign in the variable to
the left of the equals sign
+ (addition):
Used to return the sum of the two operands
- (subtraction):
Used to return the difference of the two operands
*(multiplication):
Used to return the product of the two operands

/(division):
%(modulo):

Used to return the quotient of the two operands


Used to calculate the remainder when one integer is divided by another

3. Comparison Operators
Comparison operators are used in programming to determine the relationship between two different
variables, usually as event triggers in program flow. These operators include:


== (Equal):


Used to determine if two values are equal to one another

!= (Not equal):

Used to determine if two values are not equal to one another

> (Greater than):

Used to determine if a value is greater than another value

< (Less than):

Used to determine if a value is less than another value

>= (Greater than or equal to) Used to determine if a value is greater than or equal to another
value.

<= (Less than or equal to)
Used to determine if a value is less than or equal to another
value.

Comparison operators are relatively self explanatory and are extremely useful for use in program flow
and direction. Uses for these operators are discussed in more depth in section 4.

4. Array Data Structures


In programming, Data Structures serve to organize data for easy storage and access during normal
program execution. While there are several different types of structures in C, the scope of this class will
only cover Array Data Structures.
Array Data Structures, more commonly referred to as Arrays, are essentially a set of memory locations
all referenced by the same variable name. When Arrays are declared, they are initialized for a single data
type, and throughout the program can only store data of that type. The syntax for declaring an Array is
as follows:
int Array_Example[100];
In this example, the name of the Array is Array_Example, it has been initialized to store ints, and has
100 elements, or memory locations. In order to access a specific location in the array, the program uses
the array index, which goes from zero up until one less than the size of the array. Thus, for the example
above, the array index goes from 0 to 99 to access each of the elements in the array. It is very important
to remember that in the C language, indexing starts with zero. It is a very common mistake to start
counting from 1 when indexing through an array, but this will result in referencing a memory location
that is not within the array. In the example above, trying to reference the array location:
Array_Example[100];
would return whatever value happened to be in that memory location. Once an array has been
declared, its size cannot be changed, so proper consideration when beginning to write the program is
required in order to not run out of space. The proper syntax for referencing or storing to a specific
location is given below (similar to the example above):

Array_Example[9] = 5;
Array_Example[9];
In the first part of the example, the 10th location in the array is accessed (remember that arrays begin
indexing from zero), and used to store the integer value 5. In the second part of the example, that same
location is referenced, which then returns whatever integer value is stored within, in this case, 5.

5. Program Execution
In programming the Arduino microcontroller, a set of instructions is written in proper C syntax
(commonly referred to as code), which when compiled, utilizes the processor to carry out specific
tasks or calculations. This process is called the Program Execution, and refers to the sequences of simple
actions that are explicitly written into the code. In general, code is executed from the top to the bottom,
similar to how one would read a book. In this way, a variable being stored, followed by an arithmetic
operation will make use of the initial variable value because it is executed line by line, top to bottom.

initial_variable = 5;
new_variable = initial_variable + 10;
final_variable = new_variable*2;

This example code stores 5 as the value for initial_variable, then adds 10 to it and stores it in
new_variable. The value stored in new_variable, in this case 15, is then multiplied by 2 and stored
as the value of final_variable. (So the value of final_variable is 30 at the end of the program
execution). This general top to bottom program execution is how all programs execute except when
modified by loops and if statements.

5.1 For-Loops
For loops sections are characterized by sections of code that are repeated a certain number of times.
They are classified as an iterative statement due to the fact that each time the loop is repeated, a loop
variable is iterated either upwards or downwards. The general syntax of a for loop is given below:

for(int i = 0; i < 10; i = i + 1){
Code within Loop to be repeated
}

In the above example, the loop variable is i, initialized as zero. The code executes as long as i is less than
10, and i iterates by 1 at the end of each repetition. Any statements or assignments that are contained
within the squiggly brackets { } will be repeated from top to bottom each time the loop is executed,
which in this case is 10 times. The iterator i can also be referenced within the loop which is often useful
for such operations as assigning values to individual memory locations in an array. An example of this
can be seen below.

int example_array[10];
for(int i = 0; i < 10; i = i + 1){
example_array[i] = i;

}

In this example code, the example_array is initialized to hold integers, and has 10 different locations. In
the for loop that follows, each time the for loop executes, it accesses the particular location
corresponding to the iteration that it is on, and then stores the iteration in that location. For example,
on the sixth iteration of the for loop, i will equal 5 (remember that in this example, i starts counting at
0), it will access the 6th memory location of example array, and store a 5 in that location (which
corresponds to the value of i). At the end of this code, the example_array would look like:

example_array = [0 1 2 3 4 5 6 7 8 9];

Note: For loops do not need to count upwards, nor do they need to count by 1. In the example below,
the for loop begins at 100, and iterates downwards by 5 until it reaches 25. In this way, for loops can be
iterated in many different ways depending on the application.

for(int i = 100; i > 25; i = i -5){
Code within Loop to be repeated
}

5.2 While-Loops
While loops are loops that repeat until a certain condition is met. Essentially, the loop continues to run
over and over while the stopping criterion has not been met. Once the stop condition has been met,
then the while loop exits and the program continues. The general syntax of a While loop is given below:

int i = 0;
while(i < 10){
Code within loop to be executed
i = i + 1;
}

In the above example, i is declared as an integer and initialized to 0. The while loop is then entered and
will continue to repeat until i is not less than 10. At the end of the while loop, i is increased by 1 each
time the loop executes. This example while loop does the exact same thing as the for loop example in
the previous section.

5.3 If-statements
If statements are another method for controlling program flow and execution. If statements (sometimes
referred to as if-then statements) are blocks of code that will only execute if a certain condition has
been met. If the condition has not been met, then the program will skip over that section of code as if it
does not exist. Standard C syntax for if statements is given below with the conditional statement in
parentheses directly following the if.

if(i == 10){
Code to Execute if Condition is met
}


In the above example, if the value of the variable i is equal to 10, then the code within the if statement
will execute, otherwise, the code will be ignored as the program executes. If-statements can also be
modified to become if-else statements, as in the code given below:

if(i == 10){
example_variable = 5;
}else{
example_variable = 1;
}

In this example, if the value of the variable i is equal to 10, then example_variable will be set to equal 5.
If i is equal to anything other than 10, then example_variable will be set to equal 1.

You might also like