Hardware Reference
In-Depth Information
So what exactly is a library? Sketches are written in a form of C, and a library is
simply an extension, written in either C or C++. When you create a function in
your sketch, you can call it inside the same sketch. A library has a collection of
functions that can be reused in multiple sketches. When you import a library:
functions are made available, and you can call one, several, or all the functions
in the library as needed. You could also call none of the functions, but that
would be a bit of a waste.
There are several advantages to libraries; by hiding away all the long func-
tions, your sketch is made simpler. For example, if talking to a new external
component, the library can tell your sketch how to read the data from the com-
ponent. First, pull this output high, then send some binary data, wait for a few
milliseconds, retrieve binary data, sort that data, perform some calculations,
and then return the data. All this, just to return the temperature or the ultra-
violet index? Well, you always need to follow the same process, but it can be
taken care of by a function. By putting all this code in a function, your sketch
is clearer, and you even use less memory because the sketch can call one piece
of code several times, instead of having different copies of the same function
in memory. It also makes maintenance easier; if you have several sketches that
use the same functions, updating the library makes those changes immediately
available to the sketches that use them.
Finding Libraries
Often, the most difi cult part of using an external library is i nding it in the
i rst place, and even that isn't hard. Some hardware manufacturers develop
libraries designed specii cally for their shields or breakout boards, and these
are available on the company's site. For example, Adafruit often has a tutorial
for the breakout boards that it sells, showing how to connect it and typically
with some example code. On these pages, you often i nd a link to download
the library they created to interface with the component.
Some electronic components do not require breakout boards but are still complex
enough to merit their own library. In Chapter 10 you saw how to create a wireless
device that helps keep houseplants happy. The DHT-11 humidity sensor is a rather
complex device, and the code was a little difi cult. I don't expect every Arduino
user to write code like that. To help beginners use these devices, a DHT-11 library
Search WWH ::

Custom Search