Back to Parent

int PIRpin = D1; //sets PIR equal to pin D1

int LEDpin = D0; //sets LED equal to pin D0

int SERVOpin = A5; //sets servo control to pin A0
Servo myServo;
int servoPos = 0;

boolean isTriggered = false;//prepare counter
// Know how long to wait
long timeBeforeSomethingHappens = 10 * 1000;//#seconds * milliseconds
//10 seconds was used here for testing. Increase to how long you want servo to run

// To Know if you're waiting for something to happen
// You'll start the counter by turning it to true
boolean counterRunnning = false;
// But you also need to know how long it's been
// since you started waiting
long counterStartedAt = 0;

void setup() {
    pinMode(PIRpin, INPUT);
    //sets pin D0 as an input
    pinMode(LEDpin, OUTPUT);

//servo inputs
    myServo.attach(A5);
    Particle.function("servo", servoControl);
    Particle.variable(  "servoPos" , &servoPos , INT );

    Particle.variable("motion",&PIRpin, INT);

    Time.zone(-4);
}



void loop() {
    digitalWrite(LEDpin,LOW);
    if (digitalRead(PIRpin) == HIGH) {
        //counter is started by PIR trigger
      startCounter();
       // event published for IFTTT
      Particle.publish( "catmotion", "The cat toy has been triggered");
    }
    else{
      digitalWrite(LEDpin,LOW);
    }

    if( counterRunnning ){
      digitalWrite(LEDpin,HIGH); // Turn on LED
      //do servo stuff for time of counter
      int new_position = random( 50, 130 );
      myServo.write( new_position );
    }

    if( checkIfCounterIsFinished() )
    {
      myServo.write(90);
      digitalWrite(LEDpin,LOW);
      // finally set the timer to false to finish
      counterRunnning = false;
    }

    // Time between each servo move
    delay( 500 );

}

void startCounter()
{
  counterRunnning = true;
  // the time now
  counterStartedAt = millis() ;
}
bool checkIfCounterIsFinished()
{
  // the counter is not running
  // so it can't be finished
  if( counterRunnning == false ){
    return false; // exit
  }
  // check if the time now
  // is after the time we started our counter
  // plus the time before something should happen
  // note : millis() returns the number of millis seconds since the
  // program started
  if( counterStartedAt + timeBeforeSomethingHappens < millis() )
  {
    return true;
  }
  return false;
}


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;
}
Click to Expand

Content Rating

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

0