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

/* * Turn an LED on with two claps, and off with two more */ //A toggling variable for the LED state to use with digitalWrite int clapCount = 0; //Will equal 0, 1, 2 or 3 void setup() { pinMode(A4,INPUT);//Center pin of sound trigger pinMode(6,OUTPUT); //LED } void loop() { const int soundThreshold = 600; //Experiment with your threshold //Change clapCount if noise detected. if (analogRead(A4) > soundThreshold){ clapCount++; //Increase the value of clapCount by 1 //clapCount is changed to the remainder of clapCount/4 clapCount = clapCount%4; delay(300); //prevent the noise from registering more than once } //clapCount%4 restricts clapCount to 0-3 if (clapCount == 2){ //Turn LED on after 2 claps digitalWrite(6,HIGH); } if (clapCount == 0){//Turn LED off after 2 more digitalWrite(6,LOW); } } //Change the clapCount%4 to clapCount%6, and the (clapCount == 2) to // clapCount == 3. How many claps does it take to turn on and off // now? // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

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.