Back to Parent

int statusLed = D0;              // choose the input pin (for PIR sensor)
int notifyLed = D5;                // LED Pin
int pirState = LOW;
int switchPin = D1;
int inputPin = D6;           // we start, assuming no motion detected
int val = 0;                 // variable for reading the pin status

int calibrateTime = 10000;      // wait for the thingy to calibrate

void setup()
{
  pinMode(switchPin, INPUT_PULLUP);
  pinMode(statusLed, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode( notifyLed, OUTPUT );     // declare sensor as input
}

void loop()
{
  int buttonState = digitalRead( switchPin );
  // if the sensor is calibrated
  if (buttonState == HIGH)
  // starts the function and turns on the light to detect motion
  {
    digitalWrite(statusLed, HIGH);
    if ( calibrated() )
  {
  // get the data from the sensor
    readTheSensor();

    // report it out, if the state has changed
    reportTheData();
  }
}
  else {
  digitalWrite(statusLed, LOW);
}

}
void readTheSensor() {
  val = digitalRead(inputPin);
}

bool calibrated() {
  return millis() - calibrateTime > 0;
}

void reportTheData() {

  // if the sensor reads high
  // or there is now motion
  if (val == HIGH) {

    // the current state is no motion
    // i.e. it's just changed
    // announce this change by publishing an eent
    if (pirState == LOW) {
      // we have just turned on
      Particle.publish("motion_detect", "done");
      // Update the current state
      pirState = HIGH;
      setLED( pirState );
    }
  } else {
    if (pirState == HIGH) {
      // we have just turned of
      // Update the current state
      pirState = LOW;
      setLED( pirState );
    }
  }
}
void setLED( int state )
{
  digitalWrite( notifyLed, state );
}
Click to Expand

Content Rating

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

0