Skip to content

Instantly share code, notes, and snippets.

@hilukasz
Created May 15, 2016
Embed
What would you like to do?
lights
int soundSensor = A1;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean lightState = false;
void setup() {
pinMode(soundSensor, INPUT);
pinMode(relay, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
pinMode(relay4, OUTPUT);
}
void loop() {
double sensorState = getSoundLevel();
double threshold = .2;
if (sensorState > threshold)
{
if (claps == 0)
{
detectionSpanInitial = detectionSpan = millis();
claps++;
}
else if (claps > 0 && millis()-detectionSpan >= 50)
{
detectionSpan = millis();
claps++;
delay(500);
}
}
if (millis()-detectionSpanInitial >= 400)
{
if (claps == 2)
{
if (!lightState)
{
lightState = true;
turnRelayOff();
}
else if (lightState)
{
lightState = false;
turnRelayOn();
}
}
claps = 0;
}
}
void turnRelayOn(){
int delayAmount = 100;
digitalWrite(relay, LOW);
delay(delayAmount);
digitalWrite(relay2, LOW);
delay(delayAmount);
digitalWrite(relay3, LOW);
delay(delayAmount);
digitalWrite(relay4, LOW);
delay(100);
digitalWrite(relay4, HIGH);
delay(100);
digitalWrite(relay4, LOW);
delay(500);
}
void turnRelayOff(){
digitalWrite(relay, HIGH);
digitalWrite(relay2, HIGH);
digitalWrite(relay3, HIGH);
digitalWrite(relay4, HIGH);
}
// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
double getSoundLevel(){
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(soundSensor);
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
return volts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment