user51241: I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/
I have combined the coding together and this is the new code that worked with the help gotten:
    #define led 4 // led to D4 
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;


void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup


void loop() {

     sound1();

} // close void loop


void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread > threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW); 
  } // end else

} //end loop


//this code works and is ok to run. can adjust the timing


user359: You set a timestamp when the sound first exceeds the threshold and only set the output high when millis() - firstDetect > 2*60*1000
//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread > threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW); 
} 


user4143: This is actually a lot harder than you might at first think.
Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power. 
An audio waveform goes both positive and negative:

The "peak" of the waveform can both be positive (above the line) or negative (below the line).
To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.  
However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal.  Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).
If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    uint16_t maximum = 0;
    uint32_t ts = millis();
    while (millis() - ts < t) {
        uint16_t sample = analogRead(pin);
        if (sample > maximum) {
            maximum = sample;
        }
    }
    return maximum;
}

Now to get the maximum over, say, a 10ms period, you can:
uint16_t maximum = getMaximum(A0, 10);

However, if you add a DC offset it gets a little more tricky, but the results will be better:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    int16_t maximum = 0;
    int16_t minimum = 0;
    uint32_t ts = millis()
    while (millis() - ts < t) {
        // The -512 here removes the DC offset from the reading. 512 is half
        // the ADC range.
        int16_t sample = analogRead(pin) - 512;
        if (sample > maximum) {
            maximum = sample;
        }
        if (sample < minimum) {
            minimum = sample;
        }
    }

    // We now have a positive value as the maximum and a negative
    // as the minimum - or zero if none went into the max or min
    // region of the waveform.  Subtract a negative from a positive
    // is like adding a positive to a positive.  But we only want
    // a positive result, so we'll get the absolute value.
    return abs(maximum - minimum);
}

Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold.  The basic method is:

Is the sound above the threshold?


Yes: Was it above the threshold before?
No: Set a timestamp and a flag to say it's above the threshold.
Yes: Has it been above > 2 minutes?


Yes: light the LED

No: Was it above the threshold before?
Yes: Has it been above > 2 minutes?


Yes: Extinguish the LED



The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing.  A simple implementation may look like:
static uint32_t wentAbove = 0;
static bool isAbove = false;
const uint16_t threshold = 300;

uint16_t maxval = getMaximum(A0, 10);

if (maxval > threshold) {
    if (!isAbove) {
        isAbove = true;
        wentAbove = millis();
    } else {
        if (millis() - wentAbove > 120000) {
            digitalWrite(13, HIGH);
        }
    }
} else {
    if (isAbove) {
        isAbove = false;
        digitalWrite(13, LOW);
    }
}

Note: all code untested.

51241: <p>I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/</p>

<p>I have combined the coding together and this is the new code that worked with the help gotten:</p>

<pre><code>    #define led 4 // led to D4 
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;


void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup


void loop() {

     sound1();

} // close void loop


void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread &gt; threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect &gt; 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW); 
  } // end else

} //end loop


//this code works and is ok to run. can adjust the timing
</code></pre>
 359: <p>You set a timestamp when the sound first exceeds the threshold and only set the output high when <code>millis() - firstDetect &gt; 2*60*1000</code></p>

<pre><code>//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread &gt; threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect &gt; 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW); 
} 
</code></pre>
 4143: <p>This is actually a lot harder than you might at first think.</p>

<p>Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power. </p>

<p>An audio waveform goes both positive and negative:</p>

<p><a href="https://i.stack.imgur.com/K7K0R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K7K0R.png" alt="enter image description here"></a></p>

<p>The "peak" of the waveform can both be positive (above the line) or negative (below the line).</p>

<p>To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.  </p>

<p>However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal.  Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).</p>

<p>If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:</p>

<pre><code>uint16_t getMaximum(uint8_t pin, uint32_t t) {
    uint16_t maximum = 0;
    uint32_t ts = millis();
    while (millis() - ts &lt; t) {
        uint16_t sample = analogRead(pin);
        if (sample &gt; maximum) {
            maximum = sample;
        }
    }
    return maximum;
}
</code></pre>

<p>Now to get the maximum over, say, a 10ms period, you can:</p>

<pre><code>uint16_t maximum = getMaximum(A0, 10);
</code></pre>

<p>However, if you add a DC offset it gets a little more tricky, but the results will be better:</p>

<pre><code>uint16_t getMaximum(uint8_t pin, uint32_t t) {
    int16_t maximum = 0;
    int16_t minimum = 0;
    uint32_t ts = millis()
    while (millis() - ts &lt; t) {
        // The -512 here removes the DC offset from the reading. 512 is half
        // the ADC range.
        int16_t sample = analogRead(pin) - 512;
        if (sample &gt; maximum) {
            maximum = sample;
        }
        if (sample &lt; minimum) {
            minimum = sample;
        }
    }

    // We now have a positive value as the maximum and a negative
    // as the minimum - or zero if none went into the max or min
    // region of the waveform.  Subtract a negative from a positive
    // is like adding a positive to a positive.  But we only want
    // a positive result, so we'll get the absolute value.
    return abs(maximum - minimum);
}
</code></pre>

<p>Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold.  The basic method is:</p>

<ul>
<li>Is the sound above the threshold?

<ul>
<li>Yes: Was it above the threshold before?</li>
<li>No: Set a timestamp and a flag to say it's above the threshold.</li>
<li>Yes: Has it been above > 2 minutes?

<ul>
<li>Yes: light the LED</li>
</ul></li>
<li>No: Was it above the threshold before?</li>
<li>Yes: Has it been above > 2 minutes?

<ul>
<li>Yes: Extinguish the LED</li>
</ul></li>
</ul></li>
</ul>

<p>The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing.  A simple implementation may look like:</p>

<pre><code>static uint32_t wentAbove = 0;
static bool isAbove = false;
const uint16_t threshold = 300;

uint16_t maxval = getMaximum(A0, 10);

if (maxval &gt; threshold) {
    if (!isAbove) {
        isAbove = true;
        wentAbove = millis();
    } else {
        if (millis() - wentAbove &gt; 120000) {
            digitalWrite(13, HIGH);
        }
    }
} else {
    if (isAbove) {
        isAbove = false;
        digitalWrite(13, LOW);
    }
}
</code></pre>

<p><sub><em>Note: all code untested.</em></sub></p>
