//Arduino Clap Light - Factory Workshop #2 #include Servo myservo; // create servo object to control a servo #define LED 2 boolean light = true; int clap = 0; int count = 0; double trigger = 0.6; //Adjust to change sensitivity of mic int timeout = 1000; //Adjust to chaange the amount of time in between claps needed to trigger the servo boolean check = false; unsigned long starttime = 0; int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz) unsigned int sample; void setup() { pinMode(LED,OUTPUT); // Pin#2 should be conencted to a 300-600 ohm resistor before the LED Serial.begin(9600); myservo.attach(9); //Pin 9 on Arduino controls serbo myservo.write (10); delay (800); } void loop() { /**************************************** Example Sound Level Sketch for the Adafruit Microphone Amplifier ****************************************/ unsigned long startMillis= millis(); // Start of sample window unsigned int peakToPeak = 0; // peak-to-peak level unsigned int signalMax = 0; unsigned int signalMin = 1024; // collect data for 50 mS while (millis() - startMillis < sampleWindow) { sample = analogRead(0); if (sample < 1024) // toss out spurious readings { if (sample > signalMax) { signalMax = sample; // save just the max levels } else if (sample < signalMin) { signalMin = sample; // save just the min levels } } } peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude double volts = (peakToPeak * 3.3) / 1024; // convert to volts Serial.println(volts); if (volts >= trigger){ Serial.print("I heard a clap!\n"); if (check) { togglelight(); resetcheck(); } else { setcheck(); } delay(50); } if (checktime() && check){ resetcheck(); } } ///////////////////////////////////////////////////////////////////////////////// bool checktime() { unsigned long currenttime = millis(); Serial.print(currenttime); Serial.print("\n"); return ((currenttime - starttime) > timeout); } void setcheck() { Serial.print("Set Check\n"); check = true; starttime = millis(); } void resetcheck() { Serial.print("------------Reset Check----------------\n"); check = false; starttime = 0; } void togglelight() { Serial.print("Toggle Light\n"); if (light) { lightoff(); } else { lighton(); } } void lighton() { myservo.write(85); digitalWrite(LED,HIGH); delay (800); light = true; } void lightoff() { myservo.write(10); digitalWrite(LED,LOW); delay (800); light = false; }