Back to Parent

Code below controls the servo motors hooked up to the Particle Photon. Pins D0 and D1 are used for the 2 servo motors.
// Code for particle servo control

/*
 * Project Ambient
 * Description: Detects amazon price changes and opens a treasure box
 * Author: Samuel Lee, Ryan Stinebaugh, Kami Chin
 * Date:
 */

int servo_pin_1 = D0;
int servo_pin_2 = D1 ;
int device_on = HIGH ;
int box_open = 0 ; //should be closed in natural state
Servo myServo1 ;
Servo myServo2 ;


//function will be exposed to cloud. args not used
//called when wave is to be performed
int servoWave(String args) {
  //perform wave
  if(device_on == LOW) {
    return 0 ;
  }
  const int leftAngle = 0 ;
  const int rightAngle = 100 ;
  const int delayPeriod = 500 ;
  int numWaves = 4 ;
  for(int w =0; w < numWaves ; w++) {
    if(w%2) {
      //odd iteration
      myServo1.write(leftAngle)  ;
    }
    else {
      myServo1.write(rightAngle) ;
    }
    delay(delayPeriod) ;
  }
  //reset position
  myServo1.write(leftAngle) ;
  delay(delayPeriod) ;
  return 1;
}

//called asynchronously
int servoOpenBox(String args) {
  if(device_on == LOW || box_open) {
    return 0 ;
  }
  const int closedAngle = 0 ;
  const int openAngle = 100 ;
  const int delayPeriod = 3000 ;
  //assumes closed
  myServo1.write(openAngle) ;
  myServo2.write(openAngle) ;
  box_open = 1 ; //signal box is open
  delay(delayPeriod) ;
  //reset position
  myServo1.write(closedAngle) ;
  myServo2.write(closedAngle) ;
  box_open = 0 ; //closed box
  return 1;

}


// setup() runs once, when the device is first turned on.
void setup() {
  // Put initialization like pinMode and begin functions here.
  myServo1.attach(servo_pin_1);
  myServo2.attach(servo_pin_2);
  //ensure it's at 0 position
  myServo1.write(0) ;
  myServo2.write(0) ;
  //test servo
  myServo1.write(100) ;
  myServo2.write(100) ;
  delay(500) ;
  myServo1.write(0) ;
  myServo2.write(0) ;
  Particle.function("servoWave", servoWave) ;
  Particle.function("servoOpenBox", servoOpenBox) ;

}

//main logic controlled by external server
void loop() {
  //TODO add logic to change device_on based on digital input
}
Click to Expand

Content Rating

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

0