C++ and Libraries - Programming Arduino Getting Started with Sketches (2012)

Programming Arduino Getting Started with Sketches (2012)

11
C++ and Libraries

Arduinos are simple microcontrollers. Most of the time, Arduino sketches are quite small, so using the C programming language works just fine. However, the programming language for Arduino is actually C++ rather than C. C++ is an extension to the C programming language that adds something called object orientation.

Object Orientation

This is only a short book, so an in-depth explanation of the C++ programming language is beyond its scope. The book can, however, cover the basics of C++ and object orientation. But the main goal is to increase the encapsulationof your programs. Encapsulation keeps relevant things together, something that makes C++ very suitable for writing libraries such as those that you have used for the Ethernet and LCD sketches in earlier chapters.

There are many good books on the topics of C++ and object-oriented programming. Look for the higher-rated books on the topic in your favorite online bookstore.

Classes and Methods

Object orientation uses a concept called classes to aid encapsulation. Generally, a class is like a section of a program that includes both variables—called member variables—and methods, which are like functions but apply to the class. These functions can either be public, in which case the methods and functions may be used by other classes, or private, in which case the methods can be called only by other methods within the same class.

Whereas an Arduino sketch is contained in a single file, when you are working in C++, you tend to use more than one file. In fact, there are generally two files for every class: A header file, which has the extension .h, and the implementation file, which has the extension .cpp.

Built-in Library Example

The LCD library has been used in the two previous chapters, so let’s look more closely and see what is going on in a little more detail.

Referring back to sketch 9-01 (open this in your Arduino IDE), you can see that the include command includes the file LiquidCrystal.h:

Image

This file is the header file for the class called LiquidCrystal. This file tells the Arduino sketch what it needs to know to be able to use the library. You can actually retrieve this file if you go to your Arduino installation folder and file and find the file libraries/LiquidCrystal. You will need to open the file in a text editor. If you are using a Mac, then right-click on the Arduino app itself and select the menu option Show Package Contents. Then navigate to Contents/Resources/Java/libraries/LiquidCrystal.

The file LiquidCrystal.h contains lots of code, as this is a fairly large library class. The code for the actual class itself, where the nuts and bolts of displaying a message actually reside, are in the file LiquidCrystal.cpp.

In the next section, a simple example library will be created that should put the concepts behind a library into context.

Writing Libraries

Creating an Arduino library might seem like the kind of thing that only a seasoned Arduino veteran should attempt, but actually it is pretty straight-forward to make a library. For example, you can convert into a library the flashfunction from Chapter 4 that causes an LED to flash for a specified number of times.

To create the C++ files that are needed to do this, you will need a text editor for your computer—something like TextPad on Windows or Text-Mate on Mac.

The Header File

Start by creating a folder to contain all the library files. You should create this folder inside the libraries folder of your Arduino documents folder. In Windows, your libraries folder will be in My Documents\Arduino. On the Mac, you will find it in your home directory, Documents/Arduino/, and on Linux, it will be in the sketchbook directory of your home directory. If there is no libraries folder in your Arduino, then create one.

This libraries folder is where any libraries you write yourself, or any “unofficial” contributed libraries, must be installed.

Call the folder Flasher. Start the text editor and type the following into it:

Image

Save this file in the Flasher folder with the name Flasher.h. This is the header file for the library class. This file specifies the different parts of the class. As you can see, it is divided into public and private parts.

The public part contains what looks like the start of two functions. These are called methods and differ from functions only insofar as they are associated with a class. They can be used only as part of the class. Unlike functions, they cannot be used on their own.

The first method, Flasher, begins with an uppercase letter, which is something you would not use with a function name. It also has the same name as the class. This method is called a constructor, which you can apply to create a new Flasher object to use in a sketch.

For example, you could put the following in a sketch:

Image

This would create a new Flasher called slowFlasher that would flash on pin D13 with a duration of 500 milliseconds.

The second method in the class is called flash. This method takes a single argument of the number of times to flash. Because it is associated with a class, when you want to call it, you have to refer to the object that you created earlier, as follows:

Image

This would cause the LED to flash ten times at the period that you specified in the constructor to the Flasher object.

The private section of the class contains two variable definitions: one for the pin, and one for the duration, which is simply called d. Every time that you create an object of class Flasher, it will have these two variables. This enables it to remember the pin and duration when a new Flasher object is created.

These variables are called member variables because they are members of the class. Their names generally are unusual in that they start with an underscore character; however, this is just a common convention, not a programming necessity. Another commonly used naming convention is to use a lowercase m (for member) as the first letter of the variable name.

The Implementation File

The header file has just defined what the class looks like. You now need a separate file that actually does the work. This is called the implementation file and has the extension .cpp.

So, create a new file containing the following and save it as Flasher.cpp in the Flasher folder:

Image

There is some unfamiliar syntax in this file. The method names are both prefixed by Flasher::. This indicates that the methods belong to the Flasher class.

The constructor method (Flasher) just assigns each of its parameters to the appropriate private member variable. The duration parameter is divided by two before being assigned to the member variable _d. This is because the delay is called twice, and it seems more logical for the duration to be the total duration of the flash and the gap between flashes.

The flash function actually carries out the business of flashing; it loops for the appropriate number of times, turning the LED on and off for the appropriate delay.

Completing Your Library

You have now seen all of the essentials for completing the library. You could now deploy this library and it would work just fine. However, there are two further steps that you should take to complete your library. One is to define the keywords used in the library so that the Arduino IDE can show them in the appropriate color when users are editing code. The other is to include some examples of how to use the library.

Keywords

To define the keywords, you have to create a file called keywords.txt, which goes into the Flasher directory. This file contains just the two following lines:

Image

This is essentially a two-column table in a text file. The left column is the keyword and the right column an indication of the type of keyword it is. Class names should be a KEYWORD1 and methods should be KEYWORD2. It does not matter how many spaces or tabs you put between the columns, but each keyword should start on a new line.

Examples

The other thing that you, as a good Arduino citizen, should include as part of the library is a folder of examples. In this case, the library is so simple that a single example will suffice.

The examples must all be placed in a folder called examples inside the Flasher folder. The example is in fact just an Arduino sketch, so you can create the example using the Arduino IDE. But first, you have to quit and then reopen the Arduino IDE to make it aware of the new library.

After restarting the Arduino IDE, from the Arduino IDE’s menu, select File and then New to create a new sketch window. Then from the Menu, select Sketch and the Import Library option. The Options should look something like Figure 11-1.

The libraries above the line in the submenu are the official libraries; below this line are the “unofficial” contributed libraries. If all has gone well, you should see Flasher in the list.

If Flasher is not in the list, it is very likely that the Flasher folder is not in the libraries folder of your sketches folder, so go back and check.

Image

Figure 11-1 Importing the Flasher library

Type the flowing into the sketch window that has just been created:

Image

The Arduino IDE will not allow you to save the example sketch directly into the libraries folder, so save it somewhere else under the name Simple Flasher Example and then move the whole Simple Flasher Example folder that you just saved into the examples folder in your library.

If you restart your Arduino IDE, you should now see that you are able to open the example sketch from the menu as shown in Figure 11-2.

Image

Figure 11-2 Opening the example sketch

Conclusion

There is more to C++ and to writing libraries, but this chapter should get you started. It should also be sufficient for most of what you are likely to do with an Arduino. These Arduinos are small devices and the temptation is often to overengineer solutions that could otherwise be very simple and straightforward.

That concludes the main body of this book. For further information on Arduino and where to go next, a good starting point is always the official Arduino website at www.arduino.cc. Also, please refer to the book’s website at www.arduinobook.com, where you will find errata and other useful resources.

If you are looking for help or advice, the Arduino community on www.arduino.com/forum is extremely helpful. You will also find the author on there with the username Si.