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);
  }
 } 
Haider Ali
  • 51
  • 1

3 Answers3

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.

Michel Keijzers
  • 13,014
  • 7
  • 41
  • 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/

Joe S
  • 151
  • 3
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