27
Open the
P12_Smart_Door
with Arduino IDE and upload it.
When you put your hand in front of the ultrasonic ranging sensor and make sure the distance between
your hand and ultrasonic ranging sensor should less than 10 cm, you will see the servo will rotate to
170 degrees. And the LED will light off to indicate the door is opened. Until you move your hand away
in front of the ultrasonic ranging sensor, the servo will rotate to 10 degrees and the LED will light on to
indicate the door is closed.
What will you see
1. Import the ultrasonic ranging sensor and servo library.
2. Create instances of ultrasonic ranging sensor and servo.
3. Declare the port of led and some variables to store the distance and servo angle.
4. Attach the servo to D5 port and initialize the servo and setup the led as output.
5. Read the distance from the ultrasonic ranging sensor.
6. If the value of distance less than 10 cm, make the servo rotate to 170 degrees and turn led off.
7. If the value of distance more than 10 cm, make the servo rotate to 10 degrees and turn led on.
Code overview
Code usage
Create an ultrasonic ranging sensor and servo instance object so we can get the distance and make
the servo rotate to the angle we want. For ultrasonic object, there are two parameters inside the
parentheses we need to pass. The first one is the pin of trig and the second one is the pin of echo.
Instances: Ultrasonic ultrasonic(2,3); Servo myservo;
Declare which pin the servo is connected to. Different from the other modules which use variable to
initialize which pin them should be connected to, servo use ServoObject.attach() function to tell which
pin it is connected to. For example, our code is to connect the servo to D5 port
.
Attach function: myservo.attach(5);
We use if / else statements to run the corresponding code based on the different distances detected
by the ultrasonic ranging sensor. When the distance is less than 10 cm(no people are detected), first
determine that the servo is at 170 degrees. If not, rotate the server to a 170-degree angle. If it is, then
there is nothing to do. When the distance is more than 10 cm(people are detected), first determine
that the servo is at 10-degrees. If not, rotate the server to a 10 degree angle. If it is, then there is
nothing to do.
If/else Statements: if(logic statement) {code to be run if the logic statement is true}
else {code to be run if the logic statement is false }
Summary of Contents for Crowtail Deluxe Kit
Page 47: ......