Reader small image

You're reading from  Mastering Arduino

Product typeBook
Published inSep 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788830584
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Jon Hoffman
Jon Hoffman
author image
Jon Hoffman

Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon the challenges that the field of information technology provides and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon's other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter Kara is currently working towards her black belt.
Read more about Jon Hoffman

Right arrow

Programming the Arduino - The Basics

I have been programming as long as I can remember, everything from teletypes and mainframes to personal computers and embedded devices. I have programmed games, business applications, websites and mobile apps but I can honestly say that I enjoy programming microcontroller boards like the Arduino the most.

The reason for this is with microcontrollers my programs can interact with the outside world through various sensors and motors rather than programming for simple human interaction. With microcontrollers we are only limited by our imagination and ingenuity however before we can begin conquering the world, we must first learn the basics of the Arduino programming language.

In this chapter, you will learn:

  • What variables and constants are and how to use them
  • What math functions the Arduino programming language offer
  • How to add comments to our...

Curly brackets

The left curly brackets ( { ) defines where a block of code starts and the right curly bracket ( } ) defines where it ends. We saw these brackets when we looked at the setup() and loop() functions; however, curly brackets are not limited to defining the code within a function they are also used to define other blocks of code as well. We will see examples of this in the Decision making and Looping sections of this chapter.

Whenever there is a left curly bracket there must also be a right curly bracket. We say that the curly brackets are balanced when we have an equal number of left and right curly brackets. Unbalanced curly brackets can lead to crypt compiler errors. If you are receiving very crypt and hard to understand compiler errors, you may want to begin your troubleshooting by verifying that the curly brackets are balanced.

Now let's look at semicolons...

Semicolons

A semicolon is used at the end of every statement to separate one statement from the next. If a statement does not end with a semicolon it will result in a compile-time error. The error text for forgetting a semicolon is pretty obvious and will include the line number of the statement that is missing it.

Semicolons are also used in the for loop to separate the different elements. We will look at the for loop in the Looping section of this chapter. Now let's look at how we can add comments to our code.

Comments

There are two types of comments that can be used to within our Arduino code. These are block comments and line comments. Block comments are used when the text of the comment will span multiple lines and are usually used before function calls to let the reader know what a function does. The line comments are used when a short one-line comment is needed and are usually used within function blocks to let the reader know what a specific line of code is doing.

A block comment begins with /* and ends with */. The following code shows what a block comment would look like:

/* This is a block comment
   This comment can span multiple lines
   This type of comment is usually found outside function calls
*/

A line comment starts with // and goes until the end of the line. The line comment can start at the beginning of the line or it may be after a statement ends. The following examples...

Variables

A variable is used to store information that can be referenced or manipulated within the code. A variable is given a unique name which can then be used to access the information. The name of the variable should be something that describes what the variable is so anyone that looks at the code will understand what the variable is used for. Camel case should be used when naming a variable.

Camel case is used when creating a name out of multiple words are phases where the first letter of the name is lowercase, but the beginning of each remaining word is uppercase. Some examples of camel case are ledOne, myVariable and redLedOnRightSide.

When a variable is declared it is usually a good idea to give it an initial value. This helps to avoid accidentally accessing the variable prior to initializing it. To declare a variable, we define the type of variable followed by the name...

Data types

There are numerous, built-in, data types in the Arduino programming language. In this section, we will look at the most commonly used ones. Let's begin by looking at the Boolean type.

Boolean

The Boolean data type can contain one of two possible values, true or false. The following example shows how to declare a variable to be of the Boolean type:

boolean myBool = true;

The preceding code declares a variable named myBool of the Boolean type and sets an initial value of true. Boolean types are used a lot within a standard Arduino program and all comparison operations, as we will see later in this chapter, return a Boolean value.

...

Arrays

An array is an ordered collection of variables which are of the same type. Each variable in the array is called an element, and these elements can be accessed by the location (index) in the array. When an array is defined we must declare the type of variables that will be stored in it. There are several ways that an array can be defined. The following examples show some of the basic ways to define an array:

int myInts[10];
int myInts[] = {1, 2, 3, 4};
int myInts[8] = {2, 4, 6, 8, 10};

Each of these examples defines an array of integers. The first example defines an uninitialized array of ten integers. Be careful when defining uninitialized arrays because the memory locations are never initialized, which could lead to very unexpected results.

The second example defines an array of four integers were all of the elements are initialized with values. This array is automatically...

Character arrays

We saw earlier in this chapter that we can use the character (char) type to store a single character; however, what if we wanted to store whole words or sentences? We can use an array of characters to do this. Character arrays can be initiated exactly like other arrays as the following code shows:

char myStr[10]; 
char myStr[8] = {'A', 'r', 'd', 'u', 'i', 'n', 'o', '\0'}; 

Generally, character arrays are called strings. In the preceding code, we define an uninitialized string that can contain up to ten characters and also a character array that contains the word Arduino.

You may notice that at the end of the Arduino string there is a \0 character. This character represents a null. When defining a string we should always terminate the string with the null character, this is called...

Constants

A constant is a value that never changes. In the Arduino programming language, we have two ways to declare constants. We can use the const keyword or the #define component.

The #define component enables us to give a name to a constant value prior to the application being compiled. The compiler will replace all references to these constants, with the assigned value, prior to the application being compiled. This means that the defined constants do not take up any program space in memory, which may be an advantage if you are trying to squeeze a large program into an Arduino Nano.

The #define component does have some drawbacks where the biggest drawback being if the name that is defined for the constant is also included in some other constant or variable name then the name would be replaced by the value defined in the #define component. For this reason, when I use the #define...

Arithmetic functions

The Arduino programming language includes operators that enable us to calculate the sum, difference, product and quotient of two operands. To use these operators, the two operands must be of the same type. This means, as an example, we have the ability to calculate the sum of two integer variables; however, we are unable to calculate the sum of a float variable and an integer variable without casting one of the variables forcing them to be of the same type. We will look at casting a little later in this chapter.

The following example shows how we calculate the sum, difference, product, and quotient of two variables:

z = x + y; // calculates the sum of x and y
z = x - y; // calculates the difference of x and y
z = x * y; // calculates the product of x and y
z = x / y; // calculates the quotient of x and y

When we perform a division operation there are times...

Comparison operators

The Arduino programming language includes comparison operators that enable us to compare the values of two operands. The comparison operators return a Boolean value indicating if the comparison was true or false. The following code shows how we would use these operators:

x == y // returns true if x is equal to y
x != y // returns true if x is not equal to y
x > y // returns true if x is greater than y
x < y // returns true if x is less than y
x >= y // returns true if x is greater or equal to y
x <= y // returns true if x is less than or equal to y

Now that we have seen the comparison operators that the Arduino programming language provides, let's look at the logical operators.

Logical operators

There are several logical operators included in the Arduino programming language. These operators are the AND, OR and NOT operators. The NOT operator enables us to reverse a comparison operation. The AND and OR operators enable us to combine multiple comparison operators into one step. The following code shows how to use the logical operators:

(x > 5 && x < 10) // true if x is greater than 5 and less than 10
(x > 5 || x < 1) // true if x is greater than 5 or less than 1
!(x == y) // returns true if x is not equal to y

Now let's see how we can cast a variable.

Casting

The cast operator will convert the variable type to a different type. This will enable us to perform operations, like arithmetic operations, on variables of different types. For example, if we want to add two variables where one is of the float type and the other is of the integer type, then we will need to cast one of them, so the two variables are of the same type.

One thing to note is when we cast a float value to an integer value the value is truncated and not rounded. This means that if the float variable contains the value 2.9 and we cast it to an integer, the value will be 2. With this in mind, we generally want to cast integer values to float values rather than float values to integer values even if it means the operation will take longer.

The following code shows how we could cast an integer variable as a float variable to perform arithmetic calculations:

int...

Decision making

In the Arduino programming language, we make decisions with the if statement. The if statement will check if a condition is true and if so will execute the block of code within the curly brackets.

The following shows the syntax for the if statement:

if (condition) {
  // Code to execute
}

We can use an else statement after the if statement to execute a block of code if the condition is not true.

The following shows the syntax for the if/else statement:

if (condition) {
  // Code to execute if condition is true
} else {
  // Code to execute if condition is false
}

The condition, in the if statement, can be any Boolean value or an operation that returns a Boolean result. You will find that the majority of the if statements in your code will contain comparison operations. Let's look at some code that will illustrate this:

if (varA > varB) {
  Serial.println...

Looping

The Arduino programming language has three looping statements which are the for, while and do/while loops. We will start off by looking at the for loop.

The for loop is used to repeatedly execute a block of code. The for loop is usually used to execute a block of code a specific number of times or to access elements in an array. There are three parts to the for statement. These parts are the initialization, condition, and increment.

In the initialization portion of the for statement, we initialize any variables that need to be initialized. There can be multiple initializations separated by commas, but I would recommend avoiding any initialization here that is not directly related to the for loop.

The condition portion of the for statement, expect a statement that will return either a true or false and it usually contains a conditional statement. This portion of the loop...

Functions

A function is a named block of code that performs a specific task. When a new sketch is created, the IDE or Web Editor automatically creates two functions for us as we saw in the previous chapter; however, we are not limited to only those two functions, we also have the ability to declare custom functions ourselves. The following code shows the syntax for creating a function:

type name (parameters) { } 

To declare a function, we need to declare what type the function is. The function type is the value that is returned by the function. If the function is not going to return a value, as with the setup() and loop() functions, then the function type would be void.

Once the function type is declared we define the name of the function. The function name should be something that describes what the function does. For example, if we are creating a sketch that will turn a LED...

Summary

In this chapter, we covered the basics of the Arduino programming language. The material in this chapter lays the groundwork for everything else that is covered in this book, therefore, it is important to understand the items presented here.

In the next chapter, we will look at some more advanced features of the Arduino programming language and the Arduino development environments.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Arduino
Published in: Sep 2018Publisher: PacktISBN-13: 9781788830584
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jon Hoffman

Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon the challenges that the field of information technology provides and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon's other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter Kailey earned their black belts together early in 2014, Kim (his wife) earned her black belt in December 2014, and his youngest daughter Kara is currently working towards her black belt.
Read more about Jon Hoffman