Make Your Own Arduino Library

Arduino is pretty heavily based on C++ (a computer programming language). This language relies upon things called headers, functions,and libraries. These things actually carry over to Arduino too - libraries are included at the top of your code and are used in order to simplify your project code:
#include <LiquidCrystal.h>
#include <Servo.h>
In this project I will demonstrate how to make your own Library.

Step 1: Software

There is plenty of specialized software you can use for this, but your basic text editor like Notepad should work.
*You could also try something like Notepad++ or VSCode

Step 2: Arduino Code

This is a basic Blink sketch to toggle the on-board LED:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
This code isn't very complicated, and it generally wouldn't need a library. However, for the sake of demonstration, we will make one anyway.

Step 3: Make a Library 

  1. Locate your "libraries" folder. (Arduino > libraries)
  2. Make a new folder entitled "MyLibrary" - but leave out the quotation marks
  3. Within the folder you just made, create a new .txt documents called "BlinkLED"
  4. Save the file with a .h extension 
  5. Repeat with a .cpp extension
Code to go in the .h file:
/*This file is what the .cpp file looks for when it runs*/
#include "Arduino.h"
void blinkLED(int pin, int delayTime);
Code to go in the .cpp file:
/*This is where you write the code you want to run*/
#include "Arduino.h"
#include "BlinkLED.h"

void blinkLED(int pin, int delayTime){
  pinMode(pin, OUTPUT);
  digitalWrite(pin, HIGH);
  delay(delayTime);
  digitalWrite(pin, LOW);
  delay(delayTime);  
}
Now save both files and exit.

Step 4: Include Library


Close the Arduino IDE and reopen it.  Go to Sketch > Include Library and scroll down to "Contributed Libraries."  You should see one called MyLibrary.  Click on it, and you should see:
#include <BlinkLED.h>
If the above code appears, then you're good to go. Just upload the rest of the code.
#include <BlinkLED.h>

void setup() {

}

void loop() {
  blinkLED(13, 500); //pin, frequency in milliseconds
}
Now, the only thing present in loop() is the function that we made earlier in our .cpp file.  All you have to do is specify the pin your LED is connected to and the frequency at which you want it to blink.  Now, instead of having to declare the pin an output and tell it to turn on and off, we just use our library.  All you have to do is tell it which pin you want to blink and how often to blink it.

Going further

If you want your library to do more than blink an LED, all you have to do is edit the two files from before.  If you are interested in making more complicated libraries, it may help you to learn more about C++.

Popular posts from this blog

Arduino LED Temperature Indicator

Rubber Band Gatling Gun Turret (Arduino)

DIY Plant Moisture Sensor