Back to Parent

Final sketch
/*
 * Project homehack
 * Title: Smart Bed Underglow
 * Author:Xitong Deng
 * Date: 01/28/2018
 */

int inputPin = A0;          //choose the input pin (for PIR sensor) [analog pin]

int redPin = D2;
int greenPin = D0;
int bluePin = D1;

int pirState = LOW;         //assume no motion detected when we start
int val = 0;                //variable for reading the pin status.

void setup() {
  Serial.begin(9600); //open serial connection for debugging
  Serial.println("On");

  //declare LED RRB as output
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);

  //declare sensor as input
  pinMode(inputPin, INPUT);
}

void loop() {
    //make sure the loop is working
    Serial.print("Calibrated");
    //get the data from the sensor
    readTheSensor();
    //report it out, if the state has changed
    reportTheData();
}

void readTheSensor(){
  val = analogRead(inputPin);
  Serial.println(val);
  delay(1000);
}

void reportTheData(){
    //--> when the sensor tells that motion is there
    if (val > 2000){
      if (pirState == LOW){
        Particle.publish("motion-detected"); //announce this change by publishing an event
        pirState = HIGH;
        setLED(pirState);
      }
    }
    else{
    //--> when the sensor tells that motion is no longer there
    //--> we need to turn the state into LOW and turn off the light
      if (pirState == HIGH){
        pirState = LOW;
        setLED(pirState);
      }
    }
}

void setLED (int state){ //turn on/off the led light according to state
  // digitalWrite(ledPin, state);

  digitalWrite(redPin, state);
  delay(3000);  // wait for 500 milliseconds

  digitalWrite(greenPin, state);
  delay(3000);  // wait for 500 milliseconds

  digitalWrite(bluePin, state);
  delay(3000);  // wait for 500 milliseconds

}
Click to Expand

Content Rating

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

0