// Lámpara que se enciende con aplausos y Arduino - ozandamci.com
const int soundPin = 2;
const int lampPin = 9;
const unsigned long CLAP_GAP = 150; // no cuenta dos veces el eco de un aplauso (ms)
const unsigned long COUNT_TIME = 1000; // tiempo para contar aplausos (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) {
// Un sonido tras un rato de silencio es un aplauso nuevo
if (now - lastSound > CLAP_GAP) {
if (clapCount == 0) firstClap = now;
clapCount++;
Serial.print("Aplauso: ");
Serial.println(clapCount);
}
lastSound = now;
}
// Al acabar el tiempo, comprueba cuántos aplausos se han oído
if (clapCount > 0 && now - firstClap > COUNT_TIME) {
if (clapCount == 2) {
lampOn = !lampOn;
digitalWrite(lampPin, lampOn);
Serial.println(lampOn ? "Lámpara ENCENDIDA" : "Lámpara APAGADA");
}
clapCount = 0;
}
}