//loudness sensor

int loudness;
const int micPin = A0;
const int ledPin1 = 12;

//smoothing
const int numReadings = 5; //origineel 5

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

void setup() {
  Serial.begin(9600);
  //Serial.println(9600);
  pinMode(ledPin1, OUTPUT);
}

void loop() {
  smoothing(samplesound(10));
  if (average > 40){
    digitalWrite(ledPin1, HIGH);
  }
  
  if (average < 35) { digitalWrite(ledPin1, LOW);
  }
delay(1);
  }
  
int smoothing (int sensorReading){
   // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = sensorReading;
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;

  return average;
}

 int samplesound(int sampleWindow) { //sample window: how long listen (was 50)
  unsigned long startMillis = millis();
  unsigned int peakToPeak = 0;
  unsigned int sample;

  unsigned int signalMax = 0;
  unsigned int signalMin = 1024;

  while (millis() - startMillis < sampleWindow) //*1000 : omzetten in sec
  {
    sample = analogRead(micPin);
    //Serial.println(sample);
    if (sample < 400)// toss out spurious readings
    {
      if (sample > signalMax)
      {
        signalMax = sample;  // save just the max levels
      }
      else if (sample < signalMin)
      {
        signalMin = sample;  // save just the min levels
      }
    }
       }

        peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
  Serial.print("soundlevel is: ");
  Serial.println(peakToPeak);
  return peakToPeak;
}
