Back to Parent

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


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

int servoPin = A4;
Servo myServo;
int servoPos = 0;

void setup()
{
  pinMode( ledPin, OUTPUT );
  pinMode(inputPin, INPUT);     // declare sensor as input

  // attaches the servo on the A7 pin to the servo object
    myServo.attach( A4 );

    //Register our Particle to control the servo
    Particle.function("servo", servoControl);

   // Keep a cloud variable for the current position
   Particle.variable(  "servoPos" , &servoPos , INT );

}

void loop()
{

  // if the sensor is calibrated
  if ( calibrated() )
  {
  // get the data from the sensor
    readTheSensor();

    // report it out, if the state has changed
    reportTheData();
  }
}

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 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("designingiot/s15/motion");
      // Update the current state
      pirState = HIGH;
      setLED( pirState );
      Particle.publish("I_get_home","Cominghome");
    }
  } else {
    if (pirState == HIGH) {
      // we have just turned of
      // Update the current state
      pirState = LOW;
      setLED( pirState );
    }
  }
}

void setLED( int state )
{
  digitalWrite( ledPin, state );
}
Click to Expand

Content Rating

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

0