// Arduino Clap Switch Lamp - ozandamci.com
const int soundPin = 2;
const int lampPin = 9;
const unsigned long CLAP_GAP = 150; // don't count the echo of one clap again (ms)
const unsigned long COUNT_TIME = 1000; // time window for counting claps (ms)
bool lampOn = false;
int clapCount = 0;
unsigned long firstClap = 0;
unsigned long lastSound = 0;
void setup() {
pinMode(soundPin, INPUT);
pinMode(lampPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (digitalRead(soundPin) == HIGH) {
// A sound after some silence is a new clap
if (now - lastSound > CLAP_GAP) {
if (clapCount == 0) firstClap = now;
clapCount++;
Serial.print("Clap: ");
Serial.println(clapCount);
}
lastSound = now;
}
// When the time is up, check how many claps were heard
if (clapCount > 0 && now - firstClap > COUNT_TIME) {
if (clapCount == 2) {
lampOn = !lampOn;
digitalWrite(lampPin, lampOn);
Serial.println(lampOn ? "Lamp ON" : "Lamp OFF");
}
clapCount = 0;
}
}