Home LearningBasics Creating a library

Creating a library

by shedboy71

In this example we will create a basic library, a few examples on this site flash LEDs. We will create a library that will contain a couple of functions, we will then use these in our sample sketch.

You need at least two files for a library: a header file which has the exatension .h and the source file which has the extension cpp. The header file has definitions for the library this is simply a listing of everything inside like function declarations; the source file has the actual code.

In this example we will create a library called LedFlash it will contain an initialization function and 2 functions to switch on and off the LEDs.

The header file contains various requirements, first is the comments which simply contains a description and any other information you may want to include. The next 2 lines and the last line
[c]
#ifndef LedFlash_h
#define LedFlash_h

#endif
[/c]
These are used in case someone was to accidently include the library twice, its a form of protection. You then need to have the #include “Arduino.h”, this gives you access to standard types and constants of the Arduino language. We then create our LedFlash class .

LedFlash.h
[c]
/*
LedFlash.h – Library for flashing LEDs
*/
#ifndef LedFlash_h
#define LedFlash_h

#include “Arduino.h”

class LedFlash
{
public:
void Init();
void AllOn();
void AllOff();
};

#endif
[/c]
LedFlash.cpp
[c]
#include “Arduino.h”
#include “LedFlash.h”

const int NumberLeds = 8;
const int LedPins[] = {2,3,4,5,6,7,8,9};

void LedFlash::Init()
{
for (int led = 0; led < NumberLeds; led++)
{
pinMode(LedPins[led], OUTPUT);
}
}

void LedFlash::AllOn()
{
for (int led = 0; led <= NumberLeds; led++)
{
digitalWrite(LedPins[led], HIGH);
//delay(500);
}
}

void LedFlash::AllOff()
{
for (int led = 0; led <= NumberLeds; led++)
{
digitalWrite(LedPins[led], LOW);
//delay(500);
}
}
[/c]

Copy the library into your Arduino Library folder

Now for the Arduino code
[c]
#include “LedFlash.h”

LedFlash Leds = LedFlash();

void setup()
{
Leds.Init();
}

void loop()
{
Leds.AllOn();
delay(1000);
Leds.AllOff();
}
[/c]

Share

You may also like