int servoPin = A5;
int servoPos = 0;
Servo myServo;
int ledPin = D3;
int ledValue = 0;
int mic_pin = A0;
int noise_level;
const int sampleWindow = 50;
int servoControl(String command)
{
// Convert
int newPos = command.toInt();
// Make sure it is in the right range
// And set the position
servoPos = constrain( newPos, 0 , 180);
// Set the servo
myServo.write( servoPos );
// done
return 1;
}
void setup() {
Serial.begin(9600);
myServo.attach( A5 );
myServo.write(0);
//Register our Particle to control the servo
Particle.function("servo", servoControl);
// Keep a cloud variable for the current position
Particle.variable( "servoPos" , &servoPos , INT );
pinMode(ledPin, OUTPUT);
Particle.variable("brightness", &ledValue, INT);
Particle.variable("noise_level", &noise_level, INT);
}
void loop() {
noise_level = sampleNoise( );
Serial.println( noise_level);
displayNoiseOnServo();
delay(200);
}
void displayNoiseOnServo(){
int noise_threshold = 300;
if( noise_level >= noise_threshold ){
servoPos = 90;
Particle.publish("Noise_Loud", "high" );
}
if( servoPos > 90 ){
digitalWrite(ledPin, LOW);
}else{
digitalWrite(ledPin, HIGH);
}
if( servoPos < 180 )
{
// move from 90 towards 180
servoPos++;
}
// min servo position = 180
// max servo position = 90 i.e. loud sound detected
myServo.write(servoPos);
}
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 );
// is there any difference from too low and too high and switch up?
// now see if the sample is the lowest;
if ( sample > highest_sample ){
highest_sample = sample ;
}
if ( sample < lowest_sample ){
lowest_sample = 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!
You must login before you can post a comment. .