//Clap On Lights Program //Written by: Josh Dodson (aka theblckwlf) //08/29/2016 //Use it how you wish, but give credit where credit is due. //And be a good person. //Prep variables for program const int piezo = A0; const int LED = 3; const int feedbackLED = 13; //this will hold value from piezo int clapVal; //threshold constants for clap intensity const int quietClap = 10; const int loudClap = 100; //keep track of state of light boolean lightOn = false; //keep track of number of claps int numberOfClaps = 0; void setup() { // put your setup code here, to run once: pinMode(LED, OUTPUT); pinMode(feedbackLED, OUTPUT); Serial.begin(9600); Serial.println("The light is off"); } void loop() { // put your main code here, to run repeatedly: //repeatedly listen for claps: clapVal = analogRead(piezo); if (checkForClap(clapVal) == true){ Serial.print("number of claps: "); Serial.println(numberOfClaps); } //switch state of light every 2 claps if(numberOfClaps >=2){ if (lightOn == true){ digitalWrite(LED, LOW); //update light state lightOn = false; //reset clap number numberOfClaps = 0; Serial.println("Light should be off"); Serial.print("number of claps is now: "); Serial.println(numberOfClaps); }else if (lightOn == false){ digitalWrite(LED, HIGH); //update light state lightOn = true; //reset clap number numberOfClaps = 0; Serial.println("Light should be on"); Serial.print("number of claps is now: "); Serial.println(numberOfClaps); } } } //function to determine is clap falls in appropriate volume boolean checkForClap(int value){ if(value > quietClap && value < loudClap){ //blink the LED on 13 to indicate clap is good digitalWrite(feedbackLED, HIGH); delay(50); digitalWrite(feedbackLED, LOW); Serial.print("Valid clap with value of: "); Serial.println(value); numberOfClaps++; return true; } else{ return false; } }