Hardware Reference
In-Depth Information
Chapter 12
Writing Your Own Arduino Libraries
Arduino libraries are written in standard C/C++ code and contain either a set of useful functions or an object that is
initialized and used in Arduino sketches. The advantage of this is that you can share these libraries across your own
projects and with other users. In this chapter, we will create an example “Hello World” library, a Motor control library,
and a more complex DS1631 I2C temperature sensor library.
What you need to know to write your own libraries
The choice to program libraries in C or C++ is up to you. Standard C works when using the Arduino library
conventions. If you plan to use structs and enum variables you will have to place them in a header file.
C++ gives you the ability to create objects, but since we are working with an 8-bit MCU, there is limited
memory space and usually little or no memory management. Make sure to test your code for memory use and heap
fragmentation. Remember that not everything must be an object; it is acceptable to have a set of functions that you
use as libraries without writing them from scratch for each sketch.
The major difference between Arduino sketches and Arduino libraries is that a sketch is pre-processed, meaning
that you do not have to prototype your functions or write a header file for your main sketch. For this reason, a sketch
is easy to use and a good starting place for beginners. Libraries, on the other hand, have to conform to the full rules of
C/C++. The C/C++ compiler is powerful, but if you use functions, and variables before they are defined, the compiler
will indicate an error and ultimately fail. A helpful metaphor is the idea of enrolling a course that has a required
prerequisite, but the system cannot identify what the prerequisite is.
A compiler reads from the top of the file to the bottom. If any variables or functions depend on others and one is
not defined, an error occurs. These prototypes and header files are a list of all the functions and variables used in the
sketch and library code. The only solution is to place a prototype of your function at the top of your sketch or in the
header file. For example, let's say you a have a function that adds two integers. The prototype would be:
int add(int aa, int bb);
The prototype needs only minimal information about return type, function name, and expected types that it will
encounter. The implementation, on the other hand, can be done any way that follows the rules set by the prototype.
int add(int aa, int bb) {
int res = aa + bb;
return res;
}
Another valid implementation:
int add(int aa, int bb) {
return aa + bb;
}
 
Search WWH ::




Custom Search