Make Your Own Arduino Library
In this project I will demonstrate how to make your own Library.#include <LiquidCrystal.h> #include <Servo.h>
Step 1: Software
There is plenty of specialized software you can use for this, but your basic text editor like Notepad should work.
Step 2: Arduino Code
This is a basic Blink sketch to toggle the on-board LED:
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.void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }
Step 3: Make a Library
- Locate your "libraries" folder. (Arduino > libraries)
- Make a new folder entitled "MyLibrary" - but leave out the quotation marks
- Within the folder you just made, create a new .txt documents called "BlinkLED"
- Save the file with a .h extension
- 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:
If the above code appears, then you're good to go. Just upload the rest of the code.#include <BlinkLED.h>
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.#include <BlinkLED.h> void setup() { } void loop() { blinkLED(13, 500); //pin, frequency in milliseconds }