gadhagod
Published

Clap-Controlled Lights That You Can Actually Use

Clap twice to turn on and off a bright LED.

IntermediateShowcase (no instructions)1,196
Clap-Controlled Lights That You Can Actually Use

Things used in this project

Hardware components

High Brightness LED, White
High Brightness LED, White
×1
Arduino Micro & Genuino Micro
Arduino Micro & Genuino Micro
×1
SparkFun Sound Detector (with Headers)
SparkFun Sound Detector (with Headers)
×1

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free
PCB, For DMB-4775
PCB, For DMB-4775

Story

Read more

Schematics

claplight_XEJHAtkVr1.png

Code

ClapLight

C/C++
/*
* 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;
    }
  }
}

Credits

gadhagod

gadhagod

10 projects • 8 followers

Comments