I am having trouble with my digital sound sensor. My goal: Clap 2 times and a led goes on. So I wrote this code. I don't know if it is correct or not. This happens: If I clap, from the serial monitor I don't get one HIGH, but a few (I tried changing the sensitivity of the soundsensor, but it doesn't help), but in my code I have some conditions where only 1 HIGH at a time is allowed. Thus, I don't know if my code is incorrect, or my sensor isn't working well. Can you guys help me please? This is my code:
int soundPin = 13; // Digital soundPin
int ledPin = 7;
int claps = 0; // The amount of times I clapped
int readingState ; // The first reading from the soundPin
int readingState2 ; // The second reading from the soundPin
int soundDetectionTime ; // The time after the first clap
int soundDetectionTime2 ; // The time after the second clap
int timeBetweenSounds = 1000; // The time between the sounds I want. There
is an If-statement further on.
void setup(){
pinMode(soundPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
readingState = digitalRead(soundPin); // The first reading form the
soundPin (digital pin)
Serial.println(readingState);
if (readingState == HIGH){ // If the reading from the
soundPin is HIGH, then start
timing. Also claps value
increased by 1 and the
second reading is happening.
soundDetectionTime = millis();
claps++ ;
readingState2 = digitalRead(soundPin);
if (readingState2 == HIGH){ // If the above statement is
true, then this if-statement
is executed. If the second
reading is HIGH,
soundDetectionTime two will
start counting
soundDetectionTime2 = millis(); // Also the claps get increased by 1,
so now claps = 2.
claps++;
}
}
if ((soundDetectionTime - soundDetectionTime2) > timeBetweenSounds &&
claps==2){ // If there is 1 second between the
two readings and if I clapped
twice, then LED is HIGH.
digitalWrite(ledPin, HIGH);
}
}