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 - Beyond the Basics

One of the things that I learned early on in my development career is that I can write some pretty amazing applications even if I only know the basics of the programming language that I am using; however, it usually makes the code hard to maintain and read while also adding significant development time to the project. I always tell people that are learning a language to take the time to understand some of the more advanced features of the language they are learning prior to using it for serious projects.

In this chapter, we will learn:

  • How to set the pin mode on an Arduino digital pin
  • How to get and set the values of an Arduino digital pin
  • How to get and set the values of an Arduino analog pin
  • How to use structures and unions
  • How to use additional tabs
  • How to use classes and objects

In the previous chapter, we looked at the basics...

Setting digital pin mode

In Chapter 1, The Arduino, we saw that the Arduino has several digital pins that we can connect external sensors and other devices to. Before we use these pins, we should configure them for either input or output depending on what we are using them for. To do this, we use the pinMode() function that is built into the Arduino programming language. Usually for smaller sketches we call the pinMode() function within the setup() function; however, this is not required. The following code shows the syntax for the pinMode() function:

pinMode(pin, mode);

This function is called with two parameters. The first is the number of the pin that we are setting and the second is the mode for the pin. The mode for the pin can be either INPUT, to read the value from the pin (external sensor writes a value to the pin), or OUTPUT, to set the value for the pin. The following...

Digital write

To set the value of a digital pin in the Arduino programming language, we use the digitalWrite() function. This function takes the following syntax:

digitalWrite(pin, value);

The digitalWrite() function accepts two parameters, where the first one is the pin number and the second is the value to set. We should use either HIGH or LOW when setting the value of a digital pin. The following code shows how to do this:

digitalWrite(LED_ONE, HIGH);
delay(500);
digitalWrite(LED_ONE, LOW);  
delay(500);

In the preceding code, we set the pin defined by the LED_ONE constant too HIGH and then pause for half a second. The delay() function in the Arduino programming language pauses the execution of the sketch for a certain amount of time. The time for this function is in milliseconds. After the delay() function we then set the pin defined by the LED_ONE constant too LOW and wait...

Digital read

To read the value of a digital pin in the Arduino programming language, we use the digitalRead() function. This function takes the following syntax:

digitalRead(pin);

The digitalRead() function takes one parameter, which is the number of the digital pin to read, and will return an integer value. The following code shows how we can use the digitalRead() function to read one of the digital pins on the Arduino:

int val = digitalRead(BUTTON_ONE);

With this code, the digitalRead() function will return the value of the pin defined by the BUTTON_ONE constant and put that value into the variable named val. The val variable is defined to be an integer. However, the digitalRead() function will only return a 0 or a 1. We can use the same HIGH and LOW constants that we saw in the Digital write section to see if the pin is either high or low. Using these constants are preferred...

Analog write

Analog values are written to the Arduino with the Pulse-Width Modulation (PWM) pins. In Chapter 1The Arduino, we looked at what PWM is and how they work. On most Arduino boards the PWM pins are configured for pins 3, 5, 6, 9, 10, and 11; however, the Arduino Mega has significantly more pins available for PWM functionality.

To perform an analog write, we use the analogWrite() function, which takes the following syntax:

analogWrite(pin, value); 

The analogWrite() function accepts two parameters, where the first one is the pin number and the second is the value to set. The value for the analogWrite() function can range from 0 to 255.

Let's look at a sample sketch to see how we can use the analogWrite() function to fade a led in and out:

#define LED_ONE 11

int val = 0;
int change = 5;

void setup()
{
  pinMode(LED_ONE, OUTPUT);
}

void loop()
{
  val += change...

Analog read

We read the value from an analog pin using the analogRead() function. This function will return a value between 0 and 1023. This means that if the sensor is returning the full voltage of 5V, then the analogRead() function will return a value 1023, which results in a value of 0.0049V per unit (we will use this number in the sample code). The following code shows the syntax for the analogRead() function:

analogRead(pin);

The analogRead() function takes one parameter which is the pin to read from. The following code uses the analogRead() function with a tmp36 temperature sensor to determine the current temperature:

#define TEMP_PIN 5

void setup() {
  Serial.begin(9600);
}

void loop() {
  int pinValue = analogRead(TEMP_PIN);
  double voltage = pinValue * 0.0049;
  double tempC = (voltage - .5) * 100.0;
  double tempF = (tempC * 1.8) + 32;
  Serial.print(tempC);
  Serial...

Structures

A structure is a user-defined a composite data type that is used to group multiple variables together. The variables in a structure may be of different types enabling us to store related data, of different types, together. The following code shows the syntax of how we would define a structure:

struct name {
  variable list
  .
  .
};

When a structure is defined, the struct keyword is used followed by the name of the structure. The variable list is then defined between the curly brackets.

Let's take a look at how we can create and use a structure by changing the previous sketch, which used the analogRead() function to read the TMP36 temperature, to use a structure. The first thing we need to do is to define a structure that will store the temperature information from the sensor. We will name this structure tmp36_reading, and it will contain three variables all of...

Unions

A union is a special data type that enables us to store different data types in a single definition, similar to the structure; however, only one of the members may contain data at any one time. The following shows the syntax for defining a union:

union name {
  variable list
  .
  .
};

If the syntax looks a lot like the syntax for a structure. In fact, it is the same syntax except for the struct/union keywords.

Let's see how we would use a union. The following code defines a new union:

union some_data {
  int i;
  double d;
  char s[20];
};

The preceding code defines a union named some_data that can contain an integer, double or a character string. The keyword in that last sentence is the or. Unlike the structure, which can store several different values, a union can only store one value at a time. The following code will illustrate this:

union some_data {
  int i...

Adding tabs

As you begin to work with larger and more complex projects, it quickly becomes important to divide your code up into separate workspaces because it makes your code easier to manage. To do this, in both the Arduino IDE and the Web Editor, we can add new tabs to a sketch.

To add a new tab to the Arduino IDE, click on the button with an upside-down triangle in it that is located at the upper right side of the IDE window, as shown in the following screenshot:

In the window that pops up, click on the New Tab option, and you will see an orange bar below the code section of the Arduino IDE windows. In this orange bar, you can name the new tab and then press the OK button to create the tab. The following screenshot shows how to name the new tab:

Once you click OK a new tab is created, with the name you gave it, as shown in the following screenshot:

We can create a new tab...

Working with tabs

When creating a new tab, the first thing we need to decide is what is going to the tab. For example in this section, we will create two new tabs. One will be named led.h and the other led. The led.h file will contain the constant definition, and the led file will contain code.

When we create a tab with the .h extension we are creating, what is known in the C language, a header file. A header file is a file that contains declarations and macro definitions. These tabs can then be included in the normal code tabs. In the next section, we will see another type of tab which is the cpp tab.

Once the new tabs are created, add the following code to the led.h tab:

#ifndef LED_H
#define LED_H
#define LED_ONE 3 #define LED_TWO 11 #endif

This code will define two constants, which are the pin header numbers for the two LEDs on the prototype that we built in Chapter 4,...

Object-oriented programming

Object-oriented programming (OOP) is a programming paradigm that helps us divide our code into reusable components using classes and objects. An object is designed to model something. For example, we could create an LED object that will contain the properties and functionality we want for a LED; however, before we can create an object we need to have a blueprint for it. This blueprint is called a class. Let's see how this works by creating a class that will help us control a LED.

We will start off by creating two new tabs named led.cpp and led.h. The led.h file will contain the definition for the class, and the led.cpp file will contain the code. Let's start off by adding the following code to the led.h file:

#ifndef LED_H
#define LED_H

#define LED_ONE 3
#define LED_TWO 11

class Led{
  int ledPin;
  long onTime;
  long offTime;
  public...

String library

The String library, which is part of the Arduino core libraries, enables us to use and manipulate text easier and in a more complex way then character arrays do. It does take more memory to use the String library than it does to use character arrays but it is easier to use the String library

There are numerous ways to create an instance of the String type. Let's look at a few examples here:

String str1 = "Arduino";
String str2 = String("Arduino");
String str3 = String('B');
String str4 = String(str2 + " is Cool");

Both of the first two lines create a simple string with the word Arduino in it. In the third line, a new String instance is created from a single constant character. In this line, notice that the single quote is used. The last example concatenates two Strings. There are several more constructors that enable...

Summary

This ends the introduction to the Arduino programming language. You can refer to the Arduino quick reference pages for additional information about the Arduino programming language.

You can find the reference pages here: https://www.arduino.cc/reference/en/. On this page, you will find links to information about the built-in Arduino functions and variables. That are also links to information about the operators and other Arduino language elements.

Don't worry if you do not feel comfortable writing your own Arduino programs right now because we will be writing a lot of code in the remaining chapters of this book, and by the end you should feel comfortable writing your own Arduino applications.

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