Back to Parent

Final Code
// the pin we're reading from
int mic_pin = A0;

// store the noise level / reading from the electret
int noise_level = 0;

const int sampleWindow = 50;

int servoPin = A5;

int ledPin = D0;
int lastLedValue = 0;
int speakerPin = D1;

// setup() runs once, when the device is first turned on.
void setup() {
  // Put initialization like pinMode and begin functions here.
  // We want to tell the Photon that we'll use
  // D0 as an output pin.
  Serial.println( 9600 );

  pinMode(ledPin, OUTPUT);
  pinMode(servoPin, OUTPUT);
}

// loop() runs over and over again, as quickly as it can execute.
void loop() {

  noise_level = sampleNoise( );
  Serial.println( noise_level );

  if( noise_level > 800 ){
    int brightness = map( noise_level, 0, 1000, 0 , 255 );
    Serial.println( noise_level );
    Serial.println( brightness );
    Serial.println( "\n" );
    // SpeakerT();
    lastLedValue = brightness;
    Particle.publish("tooloud");
    backnforth();
    // analogWrite(A5, 170);
    // delay(300);
  }else{
    if(lastLedValue > 0){
      lastLedValue = lastLedValue - 100;
      tone(D1,1000,1000);
      delay(1000);
    }
    if(lastLedValue <= 0){
      lastLedValue = 0;
  }
}
  analogWrite(ledPin, lastLedValue);   // Turn ON the LED pins
  delay(250);               // Wait for 1000mS = 1 second
}

void backnforth() //function to move the servo back and forth
{
  int i;
  for (int i= 0; i <3; i++){
    analogWrite(A5, 120);
    delay(2000);
    analogWrite(A5, 90);
    delay(1000);
  }
}

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_pin );
  	// 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 ;
  	}
  	if ( sample < lowest_sample ){
  	lowest_sample = sample;
  	}
  }

  Serial.print( "Highest = " );
  Serial.println( highest_sample );
  Serial.print( "Lowest = " );
  Serial.println( lowest_sample );

  int peakToPeak = highest_sample - lowest_sample;
  return peakToPeak;
}
Click to Expand

Content Rating

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

0