/*
* GND → GND
* VCC → 5V
* Gate → Pin 4
* Envelope → A0
*
* LED → 7
* LED → 9
*/
int LED0 = 7;
int firstClap;
int LED1 = 9;
// if true, the LED is on
// if false, then LED is off
bool state = false;
// when the last clapped happened
unsigned long lastClapTime;
// pin's state.
void soundISR()
{
int pin_val;
pin_val = digitalRead(PIN_GATE_IN);
digitalWrite(PIN_LED_OUT, pin_val);
}
void setup()
{
Serial.begin(9600);
// Configure LED pin as output
pinMode(PIN_LED_OUT, OUTPUT);
// configure input to interrupt
pinMode(PIN_GATE_IN, INPUT);
attachInterrupt(IRQ_GATE_IN, soundISR, CHANGE);
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
pinMode(LED0, OUTPUT);
pinMode(LED1, OUTPUT);
// when we start, LED is off
state = false;
lastClapTime = 0;
digitalWrite(LED0, LOW);
digitalWrite(LED1, LOW);
}
//
// This function returns true if person has clapped
// else it returns false.
//
bool isClapped(int sound) {
if (sound > 50) {
return true;
}
return false;
}
void toggleState() {
if (state == true) {
state = false;
digitalWrite(LED0, LOW);
digitalWrite(LED1, LOW);
} else {
state = true;
digitalWrite(LED0, HIGH);
digitalWrite(LED1, HIGH);
}
}
void loop() {
int sound = analogRead(PIN_ANALOG_IN);
unsigned long now = millis();
if (isClapped(sound)) {
delay(200);
// check if the two previos claps were within 1 second of one another
if (lastClapTime + 1000 > now) {
Serial.println("Now: " + String(now) + " LastClappedTime: " + String(lastClapTime) + " Toggling");
toggleState();
lastClapTime = 0;
delay(1000);
} else {
Serial.println("Now: " + String(now) + " LastClappedTime: " + String(lastClapTime));
lastClapTime = now;
}
}
}
Comments