We had discussed functions in the The working section of Chapter 6, Safety Box. If you would have thought that we will need to write our own function for getting the distance using our sensor, you would have been right, if it wasn't for, drum roll please....
Libraries!!
An Arduino library is a file that is a package of functions and declarations for other programs to use. Since we need to use the ultrasonic proximity sensor, instead of implementing the math ourselves, and writing our own functions, we can use the <Ultrasonic Distance Library>
, which has the functions required to calculate and work with the distance sensor.
To download and install the Arduino library, you must follow the following instructions:
NewPing
folder in libraries
.#include <NewPing.h>
gets added into your code.Now that we have downloaded and installed the library, let's move on into the project.
Soon you will see how to use the functions that are included in the library, but before that you will need to initialize the library by using a constructor that provides the library with information so that it may work properly.
The following code snippet shows how to initialize the library, by creating an object:
NewPing distanceSensor(trigger_pin, echo_pin ) ;
Here we have created an object called distanceSensor
, and passed information to it regarding which pins of the Arduino are being used for the trig and echo pin of the sensor as parameters. If we were using the pins 7 and 8 of the Arduino for the Trig
and Echo
pin respectively, the initialization would look like:
NewPing distanceSensor(7, 8 );
Understandably, this concept of constructors and objects may be confusing at first. Let me explain how this works by giving an analogy:
Imagine the constructor in our code to be a factory that builds cars. Now you can give the car that gets created a name, this is the object in our code. Now, we may need to tell the factory what car color we would like, and give this information to it, these are the parameters in our code.
We can even create multiple objects, if we want multiple sensors like:
NewPing Sensor1(7, 8 ); NewPing Sensor2(9, 10);
And so on.
Now that we have initialized our library, we can starts using functions and variables from it.
Let's go back to our car and factory example for a second. Now that we have our car built, we need it to do things, like drive around, close the doors etc. If our car was an object named McQueen
, and had a function called accelerate
, and openDoor
, we can use as follows:
McQueen.accelerate();
And, we can use the other function as follows:
McQueen.openDoor();
If the function needs function parameters, like by what amount you want to accelerate, you can do that too:
McQueen.accelerate(100);
We have learnt how to use functions. Let us now get our hands dirty and dig deep to code for our sensor.
18.118.200.197