PROJECT: Two-Clap Light Switch
Step 1 - Build the Project
Use a sound trigger to listen for two claps to turn on an LED. Wait for two more claps to turn off the LED. What other noises can trigger the light?
Step 2 - Upload the Code
Step 3 - Read the Walkthrough
Above the setup(), create an integer variables called clapCount. It starts as 0, but it will be used to record the number of claps the sound trigger hears.
In the setup() section of the code, set your sound trigger's center pin as an INPUT and LED as an OUTPUT.
In the loop of the code, you are first creating an integer variable that holds your soundThreshold.
The if statement checks the noise level and, if the noise is above your threshold, increases clapCount by one with the ++ operator.
Now you'll use an operator called modulo (%) to make sure that clapCount never goes above 4, but cycles back to 0 after the 4th clap. Here's how it works. When you use modulo (called "modding" something), it will divide the first number by the second number. Whatever the remainder is of that division is the modded value. If clapCount is 3 and you use 3%4, the remainder is 1. If clapCount is 17, then 17%4 is 1. A 300 millisecond delay prevents a single clap from being counted twice.
Now that clapCount is set, you can use if statements to determine what should happen with your LED. If clapCount is equal to 2, the LED is on. If clapCount is equal to 0, the LED is off. clapCount can also equal 1 or 3, but you don't want anything to change when clapCount has those values.