Back to Parent

// This value will store the last time we published an event
long lastPublishedAt = 0;
// this is the time delay before we should publish a new event
// from this device
int publishAfter = 10000;

// Create values for the servomotors
int servoPinDig1 = D3;
int servoPinDig2 = D2;
Servo myServo;
Servo my2ndServo;

// Define values for force-sensitive resistor
int fsrPin = A0;

// Create a variable to hold the FSR reading
// Remember to add a 10K Ohm pull-down resistor too.
int fsrReading = 0;

// Create global variables for the event cases
String boop = ""; // formerly eventName
String a = "b"; // for passing the right event name based on data

void setup() {
  myServo.attach( servoPinDig1 );
  my2ndServo.attach(servoPinDig2 );
  myServo.write(0);
  my2ndServo.write(180);
  Particle.subscribe(  "diot/2018/paired/team4" , handleSharedEvent );
}

void loop() {
  fsrReading = analogRead(fsrPin);
  Particle.variable("fsrCurrent",fsrReading);
  //delay(5000);
  if(fsrReading > 2500){
    // publish my event
    a = "h";
    //Particle.variable("fsrCurrent3",a); //test only
    publishMyEvent(a); //high
    // delay for a bit
    delay(100);
  }
   else{
     a = "l";
     //Particle.variable("fsrCurrent3",a); //test only
     publishMyEvent(a); //low
   }
}


// These assume servos are mounted such that rotation direction is the same
// Thus to go in opposite directions, we start at 0 and 180 degrees
// and change them both by the same magnitude (135) to cross the arms

void individualServo1(){
  myServo.write(135);
  my2ndServo.write(45);
  delay(200);
}

void individualServo2(){
  myServo.write(0);
  my2ndServo.write(180);
  delay(200);
}

void publishMyEvent(String a)
{
  // Particle.variable("fsrCurrent2",a); test only
  if( lastPublishedAt + publishAfter < millis() )
  {
    boop = "diot/2018/paired/team4" + System.deviceID();
    if (a=="h"){
      Particle.publish(boop, "A sensor is above 2500" );
      lastPublishedAt = millis();
    }else{
      Particle.publish(boop, "A sensor is below 2500" );
      lastPublishedAt = millis();
    }
  }
}

void handleSharedEvent(const char *event, const char *data)
{
  String boop2 = String( event ); // convert to a string object
  String deviceID = System.deviceID();
  if( boop2.indexOf( deviceID ) != -1 ){
  // The event was published by MY photon
  }else{
    // The event was published by the OTHER photon
    String whatDoesTheDataSay = String(data);
    if(whatDoesTheDataSay == "A sensor is above 2500"){
      individualServo1();
    }else{
      individualServo2();
    }
  }
}
Click to Expand

Content Rating

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

0