Project 4.04 There is a library for that
In this project we will learn about the benefits of using a library to save development time and frustration.
Project Code:
///////////////////////////////////////// // 4.04 - There is a library for that byte piezoPin = 12; byte SW1 = 1; bool pressed = LOW; void setup() { pinMode(piezoPin, OUTPUT); pinMode(SW1, INPUT); } void loop() { if (digitalRead(SW1) == pressed) { tone(piezoPin, 500, 100); } } /////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
What is a library? A library is a set of pre-made functions written by yourself or other people. Adding them into your program will provide additional functionality and cut down on development time significantly. They make programming much more manageable!
The library we use in the example is the “tone” library. This library is automatically included in Arduino, so you don’t have to include any headers. We’ll talk about what headers are later.
All we have to do to use it is call the tone function. See the table below for parameters:
Function Name | Parameter 1 | Parameter 2 | Parameter 3 |
---|---|---|---|
tone | Pin number that the piezo is connected to | Desired frequency | Tone duration |
This is almost exactly the function we made over the course of the last few sketches! By using this built-in library, we could have saved a lot of time and complications! This is the value of using libraries. Unless you need to, try not to re-invent the wheel. Search for a library for the part you are using. Many times, having a library or not is a huge factor in picking components.