Home‎ > ‎CS 11M‎ > ‎

Arduino Libraries


Writing Libraries and Classes

Learner Outcomes

At the end of the lesson the student will be able to:

  • Create an Arduino Library
  • Write code to define a class.
  • Separate header code from implementation code.

About Arduino Libraries

  • Software libraries are a collection of generally available programs and software packages
  • The Arduino has many libraries and we have used some of them such as when writing Serial.println()
  • We can write our own libraries and Arduino supports our creation of these libraries
  • For example, we spend time developing a good set of software functions
  • Then we can package the software into a library that we can use in other applications
  • All the Arduino libraries are written as classes -- an important topic in computer science
  • Arduino uses classes for their libraries because classes are a way to organize variables and functions into logical modules
  • By writing classes and libraries, we can make that code more easily reusable
  • Also, writing an Arduino Library is a good way to understand classes and objects

Library Folder

  • We can write our library files almost anywhere
  • However, we will eventually need to install our libraries in the library folder
  • On Linux computers the library folder is located in "Sketchbook"
  • On Windows and Apple computers the default name of the folder is "Arduino" and is located in the Documents folder Sketchbook location
  • This folder is automatically created by the Arduino IDE when installed
  • We may change the location of the library by selecting the Arduino menu File > Preferences
  • On school computers, it is easier to install contributed libraries on the Desktop

Getting Started

  • To get started with libraries, classes and objects we will start with simple projects
  • As we learn more, we can explore more complicated scenarios
  • For this lesson we will start with an RGB LED
  • So we can all follow the lesson, complete the next exercise

Header Files

  • We start creating a library by making the header file
  • We create the header file by creating a new tab and entering the name for the new files as RGB_LED.h
  • As we saw in the lab, the header file has three parts:
    1. Class declaration
    2. #include "Arduino.h"
    3. #ifndef sequence
  • In addition, we often include a block comment at the top of the file
  • The following is the header file for the RGB_LED library
  • We will next look at the parts that make up the file

Color Header (.h) File

/**
 * Color.h - Library for a representation of a color. 
 * 
 */ 

#ifndef COLOR_H
#define COLOR_H

#include <Arduino.h>

class Color {

  public:

    Color(const Color &other);
    Color();
    Color(int r, int g, int b);

    int getRed();
    int getGreen();
    int getBlue();

    void setRed(int r);
    void setGreen(int g);
    void setBlue(int b);

    string getDominantColor();

  private:

    int red;
    int green;
    int blue;
};

#endif

Class Declaration
  • Within the Color.h file we write the class declaration
  • A declaration is telling the compiler that we have something with this name and type
  • Later in our program we will need to define all the parts of the class
  • The general syntax for declaring a class is:
    class ClassName {
    public:
        constructor declarations
        function declarations
    private:
        member variables
    };
    
  • Where:
    • ClassName: the name you make up for the class
    • constructor declarations: constructor prototypes
    • function declarations: function prototypes for member functions
    • member variables: declarations of member variables (aka data fields)
  • The keyword private means the following items are available only inside the class
  • The keyword public means the following items are publicly accessible outside the class
  • In general, functions (including constructors) are declared public and variables are declared private
  • In this course, always declare member variables private

Constructor and Function Declarations

  • C++ allows us to declare constructors and functions without defining them
  • Function declarations (prototypes) have the function heading without the function body
  • For example, notice the prototype for the setGren() function:
    void setGreen(int g);
    
  • The declaration tells the compiler that we will have a function, named setGreen(), with these parameter types
  • We will define the function later in the program
  • The Arduino IDE normally creates function prototypes automatically and invisibly to us
  • However, when we define libraries we must explicitly define constructor and function prototypes

#include Statements

  • Notice the use of the #include statement
    #include "Arduino.h"
    
  • The #include statement tells the compiler (preprocessor) to include the specified file in our program
  • We need the statement to give our library access to the to the standard types and constants of the Arduino
  • This statement is automatically and invisibly included in standard (.ino) files
  • We must explicitly include the statement when writing library files
  • To use our library, programmers will need to explicitly use a #include statement as well:
    #include "Color.h"
    
  • The above statement will include out library into a sketch

#include Guards

  • Notice the use of:
    #ifndef COLOR_H
    #define COLOR_H
    ... (class declaration)
    #endif
    
  • These are know as #include guards
  • We use these constructs to avoid the problem of double inclusion
  • Once a header files is included, the compiler (preprocessor) checks if a unique value is defined
  • If the value is not defined, then it defines it and continues with the file
  • If the value is already defined elsewhere, the first ifndef fails and results in a blank file being included
  • We typically use a naming scheme of the class name followed by "_H" to define the header files

Activity: Add a Header (.h) File (5m)

  1. Open the program from the last assignment.
  2. Add a #include guard statement to the top and bottom of the Color.h file.
  3. Test the syntax of your Color.h file by pressing the verify button. 
  4. If you have problems, ask a classmate or the instructor for help as needed.

When finished, please help those around you.

Member Functions

  • The second function in our definition is known as a member function
  • We declared the member function in our header file
    int setRed(int r);
  • void setColor(int red, int green, int blue);
    
  • Since it was declared, we define the member function in our implementation file
    int Color::setRed(int r) {
      red = r;  
    }
  • We made a few small changes to include the function in our library
    1. We added Color:: in front of the function name to tell the compiler the function is a member of the class
    2. We used member variables of the class rather than global variables

Constructor Functions

  • Recall that the first member function of our class is called a constructor:
    class RGB_LED {
      public:
        RGB_LED(int redPin, int greenPin, int bluePin, bool commonAnode);
        void setColor(int red, int green, int blue);
      private:
        int _redPin;
        int _greenPin;
        int _bluePin;
        bool _commonAnode = true;
    };
    
  • The purpose of a constructor is to initialize member variables, of which we had four:
    RGB_LED::RGB_LED(int redPin, int greenPin, int bluePin, bool commonAnode) {
      _redPin = redPin;
      _greenPin = greenPin;
      _bluePin = bluePin;
      _commonAnode = commonAnode;
      pinMode(redPin, OUTPUT);
      pinMode(greenPin, OUTPUT);
      pinMode(bluePin, OUTPUT);
    }
    
  • Another purpose is to setup the Arduino as we did in the second half of the constructor
  • Notice we have the same RGB_LED:: in front of the constructor name to tell the compiler the constructor is part of the class
  • Comparing the constructor to a regular member function, what two things do you notice that are different?

Constructing an Object (Calling a Constructor)

  • Once we have a class defined, we may construct objects from the class
  • The syntax for constructing an object is:
    ClassName objectName(parameterList);
    
  • Where:
    • ClassName: the name of the class type
    • objectName: the variable of the class type
    • parameterList: the types an names of parameters
  • For example, to construct an RGB_LED object named rgb:
    RGB_LED rgb(11, 10, 9, true);
    
  • The data type of this object (variable) is RGB_LED and the name of the object is rgb
  • Whenever an object is created from a class, the following steps occur:
    1. Memory is allocated for all the member variables:
      _redPin
      _greenPin
      _bluePin
      _commonAnode
    2. A constructor is called to assign values to the member variables
  • For our example
    RGB_LED rgb(11, 10, 9, true);
    
    we ended with an object in memory named rgb with the following values:
    _redPin = 11
    _greenPin = 10
    _bluePin = 9
    _commonAnode = true

Activity: Add an Implementation (.cpp) File (5m)

  1. Open the sketch from the last exercise Activity.
  2. Make a new tab by clicking the down arrow image on the tab bar and selecting "New Tab"
  3. Enter the name for the new file as: RGB_LED.cpp
  4. Add the RGB_LED Implementation (.cpp) File defined at the top of this section.
  5. Add the following code to the sketch (.ino) file
    RGB_LED rgb(11, 10, 9, true); // construct an object
    
  6. Test the syntax of your RGB_LED.cpp file by pressing the verify button. Verify button
  7. If you have problems, ask a classmate or the instructor for help as needed.

When finished, please help those around you.

Library Examples

  • To verify our library works, it is a good idea to add an example
  • A fairly easy way to add an example is to convert our original color_cycle code to an example
  • Then we can compare our example with the starter code listed after the new example
  • As we can see, our new example file is much shorter than the original
  • It is shorter because mush of the functionality was exported to the library
  • Once we go through the trouble of creating a library, developing code using the library is much simpler

New Sketch (color_cycle.ino) File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "RGB_LED.h"

// Construct an object
RGB_LED rgb(11, 10, 9, true);

void setup() {
  // No setup needed
}

void loop() {
  rgb.setColor(128, 0, 0);
  delay(1000);
  rgb.setColor(0, 128, 0);
  delay(1000);
  rgb.setColor(0, 0, 128);
  delay(1000);
}

Original Sketch (color_cycle.ino) File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int redPin = 11;
int greenPin = 10;
int bluePin = 9;

int red = 0;
int blue = 0;
int green = 0;

// Set to false if using a Common Cathode LED
const bool COMMON_ANODE = true;

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {
  setColor(128, 0, 0);
  delay(1000);
  setColor(0, 128, 0);
  delay(1000);
  setColor(0, 0, 128);
  delay(1000);
}

void setColor(int red, int green, int blue) {
  if (COMMON_ANODE) {
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  }
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

Saving the Example in the Library (Follow Along)

  1. To save our example, we go to our working library folder and make a folder named "examples" (without the quotes).
  2. Within the examples folder, we make another folder named after the original sketch (color_cycle).
  3. We move our original color_cycle.ino code into the new color_cycle folder that is inside the examples folder.
  4. In addition, we rename our original working folder to the name of the library (RGB_LED).

Activity: Adding the Library (3m)

  1. Exit the Arduino IDE.
  2. Start the Arduino IDE and follow the menus:
    Sketch > Include Library > Add .ZIP Library ...
    
  3. In the file selection dialog window, navigate to and select the library folder (RGB_LED).

    The Arduino IDE will now copy the library into the library folder. When complete you will see the message:

    Library added message
  4. Verify the library is available by following the menus:
    Sketch > Include Library
    

    You will see the new library (RGB_LED) was added to the list.

  5. Open an explorer window and verify the library (RGB_LED) was added to the Arduino library folder.

When finished, please help those around you.

Removing a Library

  • To remove a library, we simply:
    1. Exit the Arduino IDE
    2. Delete the library from the Arduino "library" folder
  • The next time we start the Arduino IDE the library will be gone

Library Keywords

  • We should define the keywords of our library so the Arduino IDE can show them in the appropriate colors
  • To show the keywords we create a file named "keywords.txt" (without the quotes)
  • We add the following two lines to the file:
    RGB_LED	KEYWORD1
    setColor	KEYWORD2
    
  • We essentially have a two-column table in a text file
  • The left column is the keyword and right is the type of keyword
  • Class names should be KEYWORD1 and function names should be KEYWORD2
  • Put a single tab between the columns

Text Editors

  • For the keywords.txt file we need a text editor
  • A text editor is a basic tool used by programmers and is like the Arduino IDE
  • The Arduino IDE automates much of the process but that automation can get in the way of our library code
  • Some of the text editors we can use are:
  • Make sure to use a text editor in plain text mode
  • A good choice for this task is NotePad++
  • Avoid using word processing programs like Word, LibreOffice or OpenOffice
  • These programs are more difficult to save text as plain text

Activity: Add Keywords (5m)

  1. Exit the Arduino IDE.
  2. Open a text editor such as NotePad++, copy the following and paste it into the text editor.
    RGB_LED	KEYWORD1
    setColor	KEYWORD2
    
  3. Save the file as keywords.txt into the new library folder (RGB_LED).
  4. Start the Arduino IDE and navigate the following menu:
    File > Examples > RGB_LED > color_cycle
    
  5. Verify that the colors for RGB_LED and setColor have changed.
  6. If you have problems, ask a classmate or the instructor for help.

When finished, please help those around you.

Exercise 2: Finish the Library (10m)

In this exercise we finish the library.

Specifications

  1. Make sure you have finished all the activities in this lesson.
  2. Verify you have the following folders and files inside the RGB_LED folder:
    • examples (folder)
      • color_cycle (folder)
        • color_cycle.ino (file)
    • keywords.txt (file)
    • RGB_LED.cpp (file)
    • RGB_LED.h (file)
  3. ZIP the library RGB_LED folder to maintain the folder and file structure.
  4. Save your RGB_LED.zip file to submit to Canvas with the next lab.

When finished, please help those around you.

Wrap Up and Reminders

  • For the next homework, see the schedule
  • When class is over, please shut down your computer.
  • Complete unfinished exercises from today before the next class meeting
Comments