Lesson 9. Creating a library for Arduino.

Creating Arduino library

Learn to create your own library for Arduino.

Previous lesson     List of lessons     Next lesson

In the last lesson we finished creating Button class - buttons. All checked, debugged the code, and are going to use it in future projects for Arduino. But how to practically use the created class. Not very well turned out.

  • In the new program you need to copy the class description and method code. At the same time, it is necessary to select these blocks from the old program and not to confuse anything.
  • These parts of the program have long been tested, debugged and forgotten. Nevertheless, they will constantly catch the eye, increase the program code, worsen its structure and readability.
  • Even in these modules, you can accidentally bring in an error, and then copy the wrong version into the following programs.

A smart and practical solution is to create a library for an object of type Button.

 

The sequence of actions to create a library in the programs for Arduino.

The library at Arduino is nothing else than an extra class. Therefore, first of all, it is necessary to define functions for the library as a class. How to do this is described in detail in Lesson 7.

Design your functions as a class before proceeding further, and we use the ready-made Button class from Lesson 8.

The library must have at least two files:

  • header file (extension .h);
  • source file (extension .cpp).

The first file contains the description of the class itself, variables, constants. The program code is not here. And the second file contains the program code of the methods.

Name the new library Button and create the header file Button.h.

Arduino IDE does not support editing text files. You can edit library files in any development environment for C ++ or in a text editor, preferably with syntax highlighting. I use Notepad.

 

Button.h header file.

At first we will write to the file textual information about the library. We will inform there everything that we consider necessary: what is called, what is it intended for, how to use, who created it, etc. Of course, the text should be issued as a comment.

/ *
library information
* /

The rest of the contents of the h-file, we must conclude in the structure:

// check that the library is not connected yet
#ifndef Button_h      //  if the Button library is not connected
#define Button_h     //  then connect it

// ............

#endif

These directives exclude re-connection of the library.

Inside the structure should write:

#include "Arduino.h"

The #include directive instructs the compiler to include in the program code text from a file, the name of which follows the directive. In this case, the Arduino.h file will be included, containing the standard constants and variables of the Arduino language. In normal programs, it is added automatically, and for the library it must be specified explicitly.

It remains to add a description of our Button class. Fully Button.h file looks like this.

/*
Button.h - a library for digitally processing the signals of the button contacts
and signals of other components by a parallel process.

In a parallel process, one of the following methods should be called regularly:
void scanState(); // method waiting for a stable signal state
void filterAvarage(); // method of filtering the signal by the average value

As a result, signs are formed:
 
 for the scanState() method:
 - when the button is pressed flagPress = true
 - when the button is free flagPress = false
 - when the button was clicked flagClick = true

 for the filterAvarage() method:
 - with a low signal flagPress = true
 - with high signal flagPress = false
 - when the state changes from high to low flagClick = true

An object of type Button, when created, has parameters:

 - pin number to which the button or signal is connected
 - signal processing time (multiplied by the period of calling the scanState() method or filterAvarage()

Button button1 (12, 15); // create an object for the button connected to the 12 pin
 with a filter time of 30 ms (with a cycle of 2 ms)
The library developed by Kalinin Edward

http://mypractic.com/lesson-8-digital-filtering-of-signals-in-arduino-programs/
*/

// check that the library is not connected yet
#ifndef Button_h // if the Button library is not connected
#define Button_h // then connect it

#include "Arduino.h"

// signal processing class
class Button {
  public:
    Button(byte pin, byte timeButton); // constructor
    boolean flagPress; // sign button is pressed (low signal)
    boolean flagClick; // sign of a button click (front)
    void scanState(); // method waiting for a stable signal state
    void filterAvarage(); // method of filtering the signal by the average value
    void setPinTime(byte pin, byte timeButton); // set the output number and filter time

  private:
    byte _buttonCount; // filtering time counter
    byte _timeButton; // filtering time
    byte _pin; // pin number
};
#endif

 

The source file for the Button.cpp library.

At the beginning of the file we place the same text information as in Button.h. It is not known which of the files the user will study.

Next, we write #include directives to include the standard Arduino functions and the header file.

#include "Arduino.h"
#include "Button.h"

And then the method codes of our class.

The entire Button.cpp file looks like this:

/*
Button.h - a library for digitally processing the signals of the button contacts
and signals of other components by a parallel process.

In a parallel process, one of the following methods should be called regularly:
void scanState(); // method waiting for a stable signal state
void filterAvarage(); // method of filtering the signal by the average value

As a result, signs are formed:
 
 for the scanState() method:
 - when the button is pressed flagPress = true
 - when the button is free flagPress = false
 - when the button was clicked flagClick = true

 for the filterAvarage () method:
 - with a low signal flagPress = true
 - with high signal flagPress = false
 - when the state changes from high to low flagClick = true

An object of type Button, when created, has parameters:

 - pin number to which the button or signal is connected
 - signal processing time (multiplied by the period of calling the scanState() method or filterAvarage()

Button button1 (12, 15); // create an object for the button connected to the 12 pin
 with a filter time of 30 ms (with a cycle of 2 ms)
The library developed by Kalinin Edward

http://mypractic.com/lesson-8-digital-filtering-of-signals-in-arduino-programs/
*/

#include "Arduino.h"
#include "Button.h"

// method of filtering the signal by average value
// for a low-level signal flagPress = true
// for a high-level signal flagPress = false
// when the state changes from high to low flagClick = true
void Button::filterAvarage() {

  if ( flagPress != digitalRead(_pin) ) {
    // button state remains the same
    if ( _buttonCount != 0 ) _buttonCount--; // counter of acknowledgments - 1 with limitatuon to 0
  }
  else {
    // button state changed
    _buttonCount++; // +1 to the acknowledge counter

    if ( _buttonCount >= _timeButton ) {
      // the signal state reached the threshold _timeButton
      flagPress= ! flagPress; // inversion of the state sign
      _buttonCount= 0; // reset acknowledge counter

      if ( flagPress == true ) flagClick= true; // sign of the button click
    }
  }
}

// method for checking the status of the button
// when the flagPress = true button is pressed
// when the flagPress = false is free
// when you click flagClick = true
void Button::scanState() {

  if ( flagPress != digitalRead(_pin) ) {
    // flagPress flag = current button state
    // (inversion because the active state of the LOW button)
    // i.e. button state remains the same
    _buttonCount= 0; // reset acknowledge counter
  }
  else {
    // flagPress flag not = current button state
    // button state changed
    _buttonCount++; // +1 to the acknowledge counter

    if ( _buttonCount >= _timeButton ) {
      // the state of the button did not change for the time _timeButton
      // the state of the button became stable
      flagPress= ! flagPress; // inversion of the state sign
      _buttonCount= 0; // reset acknowledge counter

      if ( flagPress == true ) flagClick= true; // sign of the button click
    }
  }
}

// method of setting pin number and time of acknowledgment
void Button::setPinTime(byte pin, byte timeButton) {
  _pin= pin;
  _timeButton= timeButton;
  pinMode(_pin, INPUT_PULLUP); // define the pin of the button as an input
}

// class constructor Button
Button::Button(byte pin, byte timeButton) {
  _pin= pin;
  _timeButton= timeButton;
  pinMode(_pin, INPUT_PULLUP); // define the pin of the button as an input
}

In order for the Arduino IDE to highlight new types and methods from our library, you can create a file keywords.txt.

Button KEYWORD1

scanState KEYWORD2
filterAvarage KEYWORD2
setPinTime KEYWORD2

Each line contains a keyword, a tab (not spaces), and a keyword type.

  • KEYWORD1 defines classes;
  • KEYWORD2 defines methods.

You can download a zip archive with three Button library files here Button.zip.

 

Now you need to properly place the library files.

I did it like this:

  • Launched the Arduino IDE.
  • File -> Preferences -> Sketchbook location set D:\Arduino Projects. This I have indicated the folder of my Arduino projects (D:\Arduino Projects).
  • In this folder I created the folder libraries  (D:\Arduino Projects\libraries).
  • In the folder libraries, created the folder for the new library Button (D:\Arduino Projects\libraries\Button).
  • And already in this folder I copied the files Button.h, Button.cpp and keywords.txt.

For verification, you must close and rerun the Arduino IDE. Open Sketch -> Include Library and  make sure that there is a new Button library in the list of libraries.

 

How to use the library.

Very simple. At the beginning of the program include the header file with the directive

#include <Button.h>

Now you can use all public methods and variables of the Button class in exactly the same way as in the previous lesson.

Let's rewrite the LED control program from the previous lesson, using the Button library.

Here is the complete code of the program. (sketch_9_1)

/* Sketch_9_1 Lesson 9 Program
  * 2 buttons and an LED are connected to the Arduino board
  * Each press of button 1 inverts the state of the LED on the Arduino board
  * Each press of button 2 inverts the state of the LED on the breadboard */

#include <Button.h>

#define LED_1_PIN 13 // LED 1 is connected to pin 13
#define BUTTON_1_PIN 12 // button 1 is connected to pin 12
#define BUTTON_2_PIN 11 // button 2 is connected to pin 11
#define LED_2_PIN 10 // LED 2 is connected to pin 10

boolean ledState1; // variable for LED 1
boolean ledState2; // variable for LED 2

Button button1(BUTTON_1_PIN, 15); // create an object for button 1
Button button2(BUTTON_2_PIN, 15); // create an object for button 2

void setup() {
  pinMode(LED_1_PIN, OUTPUT); // determine the LED pins as outputs
  pinMode(LED_2_PIN, OUTPUT);
}

// cycle with a period of 2 ms
void loop() {

  button1.filterAvarage(); // call the filtering method for the average for button 1
  button2.scanState(); // call the method of waiting for a stable state for button 2

  // LED 1 control unit
  if ( button1.flagClick == true ) {
    // was the button click
    button1.flagClick= false; // reset sign
    ledState1= ! ledState1; // inversion of the state of the LED
    digitalWrite(LED_1_PIN, ledState1); // output LED status
  }

  // LED 2 control unit
  if ( button2.flagClick == true ) {
    // was the button click
    button2.flagClick= false; // reset sign
    ledState2= ! ledState2; // inversion of the state of the LED
    digitalWrite(LED_2_PIN, ledState2); // output LED status
  }

  delay(2); // delay 2 ms
}

Nothing extra. Only objects with which we work.

Good style to add examples to the library files. But in our subsequent lessons, examples will suffice.

In the next lesson we will learn how to work with hardware timer interrupts.

Previous lesson     List of lessons     Next lesson

Leave a Reply

Your email address will not be published. Required fields are marked *