Home Arduino Create your own Arduino library

Create your own Arduino library

On previous pages we created a DIY LED board and posted some examples. Now we are going to create a very basic library.

http://www.getmicros.net/diy-led-board.php
http://www.getmicros.net/led-examples-using-diy-led-board.php

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

#ifndef LedFlash_h
#define LedFlash_h

#endif

These are used in case someone was to accidently include the library twice, its a sform 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

/*
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

LedFlash.cpp

 

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

Copy the library into your Arduino Library folder

Now for the Arduino code

#include “LedFlash.h”

LedFlash Leds = LedFlash();

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

void loop()
{
Leds.AllOn();
delay(1000);
Leds.AllOff();
}

 

You may also like