We will now add a little bit to our code so that when you get closer than three feet to something, a light will turn on. Three feet is 91 centimeters, we need that number later. You can pick a different difference if you want. Every foot is about 30.5 cm.
To do this, we have to add what is called a condition. This can be done with an "if/else" statement. |
Here is an example of an if/else we can add.
Put this right after the last code's Serial Prints. This makes the light turn on if distances are between 0 and 91 cm, otherwise the light is off.
|
Example Wiring |
Full Example Code |
If you got your light to shine when you got too close to the sensor, then you can do the same thing with the buzzer instead.
Replace the light with a buzzer and see if it now buzzes when you get too close! After that works, use your breadboard by connecting a wire to GND to - and pin 13 to the + rail. Then you can plug as many lights and buzzers in parallel to the breadboard rail. See if you can control multiple things at once with the ultrasound sensor. Remember to use resistors for the lights. |
This lesson was inspired by a Dr.Duino lesson: www.drduino.com
hackaday.com/2020/04/09/ultrasonic-sensor-helps-you-enforce-social-distancing/ |