quick description of the sketch: its a clap on/off relay that turns on only when it's dark.
Cannot seem to get the relays to stay off. What happens is they are off by default then when I do the double clap to turn them on that works, after this I double clap to turn them off and then go off then immediately go on again. I can get a single relay to work perfectly but when I uncomment the rest there seems to be a problem.
I am assuming it has something to do with the delay for the clap sensor, but I am not entirely sure-- I have tried quite a few things to try to resolve it but am really lost as to why this might be happening. ideas?
int soundSensor = A2;
int relay = A0;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
int claps = 0;
long detectionSpanInitial = 0;
long detectionSpan = 0;
boolean clapState = false;
int doubleClap = 0;
//Light sensor
int photocellPin = A1; // the cell and 10K pulldown are connected to a1
int photocellReading; // the analog reading from the sensor divider
int LEDbrightness;
//int delayValue = 100;
int photoSensor = 0;
void setup() {
pinMode(soundSensor, INPUT);
pinMode(relay, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(relay3, OUTPUT);
pinMode(relay4, OUTPUT);
Serial.begin(9600);
}
void loop() {
/////////////
// photo sensor
////////////////////
photocellReading = analogRead(photocellPin);
photocellReading = 1023 - photocellReading;
LEDbrightness = map(photocellReading, 0, 1023, 0, 255);
if(photocellReading > 500){
photoSensor = 0;
}
if(photocellReading < 500){
photoSensor = 1;
}
/////////////
// clap sensor
/////////////////////
int sensorState = digitalRead(soundSensor);
//erial.println(sensorState);
if (sensorState == 1)
{
if (claps == 0)
{
detectionSpanInitial = detectionSpan = millis();
claps++;
}
else if (claps > 0 && millis()-detectionSpan >= 50)
{
detectionSpan = millis();
claps++;
}
}
if (millis()-detectionSpanInitial >= 500)
{
if (claps == 2)
{
if (doubleClap == 0)
{
doubleClap = 1;
}
else if (doubleClap == 1)
{
doubleClap = 0;
}
}
claps = 0;
}
if(doubleClap == 1 && photoSensor == 0){
digitalWrite(relay, LOW);
digitalWrite(relay2, LOW);
digitalWrite(relay3, LOW);
digitalWrite(relay4, LOW);
Serial.println("off");
}
else{
digitalWrite(relay, HIGH);
digitalWrite(relay2, HIGH);
digitalWrite(relay3, HIGH);
digitalWrite(relay4, HIGH);
Serial.println("on");
};
}