PROJECT: Sound Light Switch
Step 1 - Build the Project
Use a sound trigger to turn an LED on and off when it 'hears' a loud noise.
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
In this code, you'll keep track of whether an LED is on or off with a variable. Then, you'll use sound to trigger a reversal of that variable.
Above the setup, create an integer variable called LEDState. This variable has to exist above the setup because you use it in both the setup() section and the loop() section of the code. If you put a variable in the setup, you can't use it in the loop without declaring it again.
Within the setup(), set your sound trigger as an INPUT and your LED as an OUTPUT.
Create a constant integer variable in the top of the loop. Experiment with this value. A clap or a snap should be able to turn the light on. The sound trigger can read values from 0-1023
If the reading from the sound trigger pin is greater than the value of soundThreshold, the 'if' statement is true and the code inside the statement will run. Otherwise, the loop simply starts over.
Inside the if statement, you are using the digitalWrite() command to send either a HIGH or LOW signal to pin 13. Instead of HIGH or LOW, you'll use the value of the variable LEDState. A value of 1 corresponds to HIGH and 0 corresponds to LOW.
After you write the LEDState to the LED, you want to 'reverse' its value. To do that, you set LEDState equal to 1- LEDState. Imagine that LEDState was 0. 1 - 0 = 1, so now LEDState is 1. Imagine that LEDState was 1. 1 - 1 = 0, so now LEDState is 0. This is a quick way to flop back and forth between 0 and 1.
A short delay prevents a single noise from being caught twice in the loop.
Now the next time the loop runs, LEDState will be opposite what it was before, so when a noise triggers LEDState to be written to the variable, the action of the LED will be opposite.