I recently had to write a custom library and found the online tutorials lacking in some detail, so wanted to document the process myself for later reference.
The basic structure of an Arduino library is to have the source code for C++ classes (.h and .cpp files) in the root directory and then have example Arduino sketches in an examples folder. It is also recommended to have a keywords.txt file containing method names that the Arduino IDE should highlight as keywords.
For example, let’s assume we are building a library for blinking an LED, we would have the following files in the project.
Editing the source
The example sketches will need to contain an
#include to include the LED header file, but the Arduino IDE will only find this file if the library is already installed into the IDE’s libraries folder, so this is a problem when you are currently writing the library! There are several solutions to this issue. From worst to best, the are:
Copy files to libraries folder after changes
This is not a good solution as it requires maintaining two copies of each file and it will get confusing very quickly.
Develop directly in the libraries folder
This is not an elegant option and requires changing file permissions if you are using Linux. It would probably work OK on Windows.
My preferred option is to create a symlink under the IDE’s libraries folder to link to the source code. For example, if my library project is at ~/git/blink than I would run the following commands to create a symlink:
ln -s ~/git/blink blink
With this approach, there is a single copy of each file. The Arduino IDE can be used to edit the example sketches (from ~/git/blink) and another editor can be used to make changes to the library files referenced from the sketch (the Arduino IDE assumes that all files under the libraries path are read-only, even if they aren’t … at least, this is the case on Linux).