Back to Parent

/*This project is to develop a microphone that can tell me when the sound coming through my door is too loud only at time when I want to hear that.
Press the button to turn on listening mode
Listen for the Decibels to get louder than a specific number of Decibels
Send Message to phone telling me to turn it down
Wait 1 minute(s) and see if the sound has gone down
*/
int led = D0;//Led Pin
int mic = A0;//Led mic
int btn = D2;//Led btn
int sample = 0;//Current mic reading at a specific time
bool dbLevel = FALSE;//initialize the Microphone
bool ledState = FALSE;//initialize the LED
int btnState = LOW;// initialize the button
int sampleWindow = 50;//sample every 50ms
int toggle = 0;// The power is Off
bool sampling = false;
// When was it last published
unsigned long lastPublishTime=0;
void setup(){
  pinMode(btn, INPUT_PULLUP);
  pinMode(mic, INPUT);
  pinMode(led, OUTPUT);
  Particle.variable("Noiselevel", &sample, INT);
  Particle.variable("Tooloud",&dbLevel);
  Particle.variable("button", &btnState);
  Serial.begin(9600);
  digitalWrite(led, LOW);
}
void loop(){
  TurnOn();
  if( sampling ){
    sample = sampleNoise();
      // if it's too loud...
      if( dbLevel ){
          publishAlert();
      }
  }

  delay(100);
}
void TurnOn()
{
  // find out if the button is pushed
  // or not by reading from it.
  int currentButtonState = digitalRead(btn);
  if( currentButtonState == LOW && btnState != currentButtonState ){
      sampling = !sampling;
      digitalWrite(led, sampling);
  }
  btnState = currentButtonState;
}
//function for sampling noise
int sampleNoise()
{
  unsigned long startMillis = millis(); // Start of sample window
  int highest_sample = 0;
  int lowest_sample = 1000;
  // collect data for 50 mS
  while (millis() - startMillis < sampleWindow)
  {
    int sample = analogRead( mic );
    // invert the range, and convert it to a percent
    sample = map( sample, 0, 4095, 1000, 0 );
    // now see if the sample is the lowest;
    if ( sample > highest_sample ){
      highest_sample = sample;
    }
    else{
      lowest_sample = sample;
    }
  }

  int peak_to_peak = highest_sample - lowest_sample;

  if( peak_to_peak > 400 ){
    dbLevel = TRUE;
  }else{
    dbLevel = FALSE;
  }

  return peak_to_peak;
}
void publishAlert()
{
  if(millis()-lastPublishTime>60000)
  {
      Particle.publish("diot2017/elvin/too_loud" );
      lastPublishTime = millis();
  }
}
Click to Expand

Content Rating

Is this a good/useful/informative piece of content to include in the project? Have your say!

0