Make Your Own Arduino Library
by millerman4487 in Circuits > Arduino
18934 Views, 8 Favorites, 0 Comments
Make Your Own Arduino Library
View this project on my website!
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 <Servo.h> #include <liquidcrystal.h>
In this project I will demonstrate how to make your own Library.
Software
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.
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"
- Open the file in your editor
- Save the file with a .h extension (file > save as)
- Repeat (same title) 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.
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
If the above code appears, then you're good to go. Just upload the rest of the code.
#include
void setup() {
}
void loop() {
blinkLED(13, 500); //pin, frequency in milliseconds
}
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++.