5

I have written the following code for lighting an LED on a clap ( using sound sensor) that I have connected via a resistance of 330 OHM on pin number 4.

However, when I clap once, close to the sound sensor, it does not lights the LED. But it only lights the LED if I provide prolong exposure to sound ( more than 6 seconds) on the sound sensor.

How can I improve this , so that even if I clap once for a seconds duration, the LED glows?

int soundSensor=10;
int LED=4;

void setup() 
{
 Serial.begin(9600);  
 pinMode(soundSensor,INPUT);
 pinMode(LED,OUTPUT);
}

void loop() 
{
  int SensorData=digitalRead(soundSensor); 
  if(SensorData==1)
  { 

     digitalWrite(LED,HIGH);
  delay(3000);

     Serial.println("LOUD, LOUD");
     delay(1000);
  }
    else
  {

     digitalWrite(LED,LOW);
     Serial.println("SLOW, SLOW");
     delay(1000);
  }
 } 
2
  • 3
    One thing is that your program does a lot of waiting, the loop only runs once every second when there's no sound. Also the delay could be in the sensor itself, make clear what sensor you're using. Ideally you would also include a schematic to show how it is connected. Commented Jun 13, 2018 at 12:07
  • We need to see the circuitry for your sound sensor as well.
    – Elliot Alderson
    Commented Jun 13, 2018 at 12:11

3 Answers 3

6

I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.

So check more often (reduce the delays) and check for so many sound detections within one second.

Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.

2
  • 4
    Or use an interrupt.
    – JRE
    Commented Jun 13, 2018 at 12:33
  • @JRE Thanks for the good remark, I updated my answer. Commented Jun 13, 2018 at 13:58
5

Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input (like clapping).

Using the attachInterrupt() function is the way to go here!

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

3

Depending on sensor , simple modification with series diode to detect impulse and hold decaying slow with say 0.01uF to and 10 MOhm to 0V will detect 1st time and stretch pulse ~ 0.01u*10M =0.1s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.