Schedule‎ > ‎

11B: Arduino Libraries

^ top

^ top

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.

^ top

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

^ top

Exercise 1: Setup RGB LED Breadboard (10m)

In this exercise we breadboard the RGB LED so we can create an RGB_LED library. Start by breadboarding the following circuit.

Parts List

  • Arduino board
  • USB cable
  • Solderless breadboard
  • RGB LED (common anode assumed)
  • 3x resistors, all the same value in the range of 220-600Ω
  • Jumper Wires

Breadboard Layout

RGB LED breadboard

Specifications

  1. Start with the Arduino unplugged and breadboard the circuit shown in the image above.
  2. After breadboarding, start the Arduino IDE, copy the starter code below, and paste the code into the main IDE window.
  3. Save the project using the name color_cycle (File > Save As...) to a convenient location like the Desktop
  4. Compile the sketch to verify you copied the starter code correctly.
  5. Upload your code to test that it works correctly.

    You should now see the RGB LED cycle through the colors red, green and blue. If you have problems, ask a classmate or the instructor for help.

  6. Save your color_cycle sketch as we will be adding to it in subsequent exercises.

When finished, please help those around you.

Sketch color_cycle

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
const int RED_PIN = 11;
const int GREEN_PIN = 10;
const int BLUE_PIN = 9;

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

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
}

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

void setColor(int red, int green, int blue) {
  if (COMMON_ANODE) {
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  }
  analogWrite(RED_PIN, red);
  analogWrite(GREEN_PIN, green);
  analogWrite(BLUE_PIN, blue);
}

^ top

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
  • 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

RGB_LED Header (.h) File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
  RGB_LED.h - Library for controlling an RGB LED.
  @author Ed Parrish
  @version 1.0 11/14/2015
*/
#ifndef RGB_LED_H
#define RGB_LED_H

#include "Arduino.h"

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;
};

#endif

Class Declaration

  • Within the RGB_LED.h file we write the class declaration
    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;
    };
    
  • 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 avaialable 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 setColor() function:
    void setColor(int red, int green, int blue);
    
  • The declaration tells the compiler that we will have a function, named setColor(), 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 "RGB_LED.h"
    
  • The above statement will include our library into a sketch

#include Guards

  • Notice the use of:
    #ifndef RGB_LED_H
    #define RGB_LED_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 1: Add a Header (.h) File (5m)

  1. Open the sketch from the last exercise (Exercise 1).
  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.h
  4. Declare the three parts of the header file as discussed in this section:
    1. Class declaration
    2. #include "Arduino.h"
    3. #include guard
  5. Add a #include statement to the top of the color_cycle.ino file.
    #include "RGB_LED.h"
    
  6. Test the syntax of your RGB_LED.h 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.

^ top

Implementation Files

  • The implementation file is where we write our constructor and function definitions
  • In the definitions, we must write all the code needed for a constructor or function
  • The implementation file ends in .cpp, such as RGB_LED.cpp
  • We create the implementation file by making a new tab and entering the name for the new file as RGB_LED.cpp

RGB_LED Implementation (.cpp) File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include "Arduino.h"
#include "RGB_LED.h"

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);
}

void RGB_LED::setColor(int red, int green, int blue) {
  if (_commonAnode) {
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  }
  analogWrite(_redPin, red);
  analogWrite(_greenPin, green);
  analogWrite(_bluePin, blue);
}

Member Functions

  • The second function in our definition is known as a member function
  • We declared the member function in our header file
    void setColor(int red, int green, int blue);
    
  • Since it was declared, we define the member function in our implementation file
    void RGB_LED::setColor(int red, int green, int blue) {
      if (_commonAnode) {
        red = 255 - red;
        green = 255 - green;
        blue = 255 - blue;
      }
      analogWrite(_redPin, red);
      analogWrite(_greenPin, green);
      analogWrite(_bluePin, blue);
    }
    
  • The member function does the same job as our original setColor() function
  • We made a few small changes to include the function in our library
    1. We added RGB_LED:: 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 2: 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.

^ top

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 much 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_cycle2.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(255, 0, 0);
  delay(1000);
  rgb.setColor(0, 255, 0);
  delay(1000);
  rgb.setColor(0, 0, 255);
  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(255, 0, 0);
  delay(1000);
  setColor(0, 255, 0);
  delay(1000);
  setColor(0, 0, 255);
  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);
}

Creating the Library Struture (Follow Along)

  1. Copy the color_cycle2 code and save it to your working directory (NOT the Documents->Arduino->libraries directory)
  2. Create a folder with your library name: RGB_LED
  3. Inside the RGB_LED folder, create a folder named examples
  4. Within the examples folder, we make another folder named color_cycle2.
  5. We move our color_cycle2.ino code into the new color_cycle2 folder that is inside the examples folder.
  6. Copy RGB_LED.cpp and RGB_LED.h into the RGB_LED folder.
  7. Your RGB_LED folder should contain the following:
  • examples (folder)
    • color_cycle2 (folder)
      • color_cycle2.ino (file)
  • RGB_LED.cpp (file)
  • RGB_LED.h (file)

Activity 3: 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. You can also see the example program color_cycle by ArduinoIDE->File->Examples->Examples from custom libraries (scroll down to the bottom)
  6. 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

^ top

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 4: 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.
  7. Remember that any time you make a change to any of your library files,  you will need to delete the old library file from the Arduino->libraries directory,  restart the IDE and then re-import the updated folder into the Arduino IDE.

When finished, please help those around you.

^ top

Exercise 2: Finish the Library

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_cycle2 (folder)
        • color_cycle2.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 and submit to Canvas.
  5. Remember that any time you make a change to any of your library files you need to create a new zip file.  Then you will need to delete the old library file from the Arduino->libraries directory,  restart the IDE and then re-import the updated folder into the Arduino IDE.

When finished, please help those around you.

^ top

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
^ top