Hi everyone!
I'm new to Arduino and am having a problem with this sound sensor. With the code I created for the clapper(modified someone else's), the sensor won't work if I clap more than around 10cm from the sensor, but with a code that I found and only turns on the led light for 1 second and works even when I clap 5m away and I don't know how to do the same with the clapper script.
Thanks in advance for all help!
The clapper:
int Analog_Soundpin = A0;
int ledpin = 9;
boolean flag = true;
void setup()
{
pinMode(ledpin,OUTPUT); // this pin controlled by flipflop() function
pinMode (Analog_Soundpin,INPUT_PULLUP); // keeps pin HIGH via internal pullup resistor unless brought LOW with switch
Serial.begin(9600); // just for debugging, not needed.
}
void loop()
{
if (digitalRead(Analog_Soundpin)==LOW);// check the state of switch1 every time we run through the main loop
{
delay(5); // I don't REALLY know why this delay helps, but it does.
flipflop(); // hops out of main loop and runs the flipflop function
}// end of check for button press.
// other sketch code here
} // end of main loop.
void flipflop(){ //funtion flipflop
flag = !flag; // since we are here, the switch was pressed So FLIP the boolian "flag" state (we don't even care if switch was released yet)
Serial.print("flag = " ); Serial.println(flag); // not needed, but may help to see what's happening.
if (flag == HIGH){ // Use the value of the flag var to change the state of the pin
digitalWrite(ledpin,HIGH ); // if the flag var is HIGH turn the pin on
}
if (flag == LOW) {
digitalWrite(ledpin,LOW); // if the flag var is LOW turn the pin off
}
while(digitalRead(Analog_Soundpin)==LOW); // for "slow" button release, keeps us in the function until button is UN-pressed
// If you take out this "while" the function becomes a flipflop oscillator if the button is held down.
delay(10); // OPTIONAL - play with this value. It is probably short enough to not cause problems. deals with very quick switch press.
}
The code in which the sound sensor works better:
const int ledpin=9; // ledpin and soundpin are not changed throughout the process
const int soundpin=A0;
const int threshold=40; // sets threshold value for sound sensor
void setup() {
Serial.begin(9600);
pinMode(ledpin,OUTPUT);
pinMode(soundpin,INPUT);
}
void loop() {
int soundsens=analogRead(soundpin); // reads analog data from sound sensor
if (soundsens>=threshold) {
digitalWrite(ledpin,HIGH); //turns led on
delay(1000);
}
else{
digitalWrite(ledpin,LOW);
}
}