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 will need to know that number later. You can pick a different difference away. Every foot is about 30 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 before the end of our code to do this.
Put this right after the last code's Serial Prints and the delay. What this does is if the distance is between 0 and 91 cm, then the light is on, otherwise the light is off.
|
Example Wiring |
Example Code |
The only thing we are adding is the LED to GND and pin 13. Remember to use a blue or white light if you do not want to use a resistor. If you want to use a different color light, you will need to add a 220 or 330 Ohm resistor to the light. Ask your teacher about how to do this before doing it though.
|
If you got your light to shine when you got too close to the sensor, then you can do the same thing but 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. |