Back to Parent

/* CONSTANTS & VARIABLES
------------------------------------------------------*/
//Photo resistor / photo cell input
int photoCellPin = A0;

//Store the sensor reading
int photoCellReading = 0;

//Threshold for being dark
int threshold = 2800;

int ledPin = D0;

//Pin for microphone
int micPin = A1;

//Reading noise level
int noise_level = 0;

const int sampleWindow = 50;

int servoPin = D2;
Servo myServo;
int pos=5;

int buttonPin = D3;



/* SETUP
------------------------------------------------------*/
void setup(){

  //Function that will allow direct communication between usb port, analogue reading
  Serial.begin(9600);

  //Connect the photo cell reading to the cloud to read the value on "cloud variables"
  Particle.variable("light", &photoCellReading, INT);

  Particle.variable("noise", &noise_level, INT);


  pinMode(ledPin, OUTPUT);

  // Attaches the servo on the A7 pin to the servo object

  myServo.attach(servoPin);

  pinMode(buttonPin, INPUT_PULLUP);

}

/* LOOP
------------------------------------------------------*/
void loop(){

  photoCellReading = analogRead(photoCellPin);
    if(photoCellReading > threshold){
      sampleNoise();
      noise_level = sampleNoise();
      Serial.println ( noise_level );
      if(noise_level>950){
        digitalWrite(ledPin,HIGH);
        myServo.write(5);//Open door
        Particle.publish("Open","Open");
        }
    }
  digitalWrite (ledPin, LOW);
  int buttonState = digitalRead(buttonPin);
  if( buttonState == LOW )
  {

myServo.write(90);//Close door
delay(5000); //Wait for a little bit before reading again
  }
}

  //Read to give threshold
  //Serial.print("sensor reading is");
  //Serial.println(photoCellReading);


/* FUNCTIONS
------------------------------------------------------*/

int monitorPhotoCell(){

  //Reading from sensor
  photoCellReading = analogRead(photoCellPin);
  if(photoCellReading > threshold){
    digitalWrite (ledPin, HIGH);
  }
  else {
    digitalWrite (ledPin, LOW);}
  }

int sampleNoise(){
  unsigned long startMillis = millis();
  int highest_sample = 0;
  int lowest_sample = 1000;
  while (millis()-startMillis < sampleWindow) {
    int sample = analogRead(micPin);
    sample = map (sample,0,4095,1000,0);
    if (sample > highest_sample){
      highest_sample = sample;
    }
    if(sample < lowest_sample){
      lowest_sample = sample;
    }
  }
  int peakToPeak = highest_sample - lowest_sample;
  return peakToPeak;
}

int monitorMic(){
  noise_level = sampleNoise();
  Serial.println ( noise_level );
  if(noise_level>800){
    digitalWrite(ledPin,HIGH);
    }
    else{digitalWrite(ledPin, LOW);}
  }
Click to Expand

Content Rating

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

0