Back to Parent

int servoPin = A3;
Servo myServo;
int servoPos = 0;
int count = 0;
String deviceID; 

void setup() {

 // attaches the servo on the A3 pin to the servo object

  myServo.attach( A3 );

   //Register our Particle to control the servo

   Particle.function("servo", servoControl);
   
   // Keep a cloud variable for the current position

  Particle.variable(  "servoPos" , &servoPos , INT );
  
  Particle.subscribe(  "diot/2019/paired/yoolqc7000" , handleSharedEvent );
  
  Particle.variable("publishCount", count );
  
  Particle.variable("deviceid", deviceID);
}

void loop() {
}

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 handleSharedEvent(const char *event, const char *data)
{
    // Now we're getting ALL events published using "db2018/paired/"

    // This includes events from this device.

    // So we need to ignore any events that we sent.


    // Let's check the event name

    String eventName = String( event ); // convert to a string object

    // This gives us access to a bunch of built in methods

    // Like indexOf()

    // Locates a character or String within another String.

    // By default, searches from the beginning of the String,

    // but can also start from a given index,

    // allowing for the locating of all instances of the character or String.

    // It Returns: The index of val within the String, or -1 if not found.


    // We can use this to check if our event name contains the

    // id of this device


    deviceID = System.deviceID();

    // device id = 0123456789abcdef

    // event = "diot/2019/paired/0123456789abcdef"


    if( eventName.indexOf( deviceID ) != -1 ){
      // if we get anything other than -1

      // the event came from this device.

      // so stop doing stuff

      return;
    }
    count = count + 1;
    if (count >= 7){
        count = 0;
    }
    // otherwise do your stuff to respond to

    // the paired device here

    // Convert

//   int newPos = data.toInt();

   // Make sure it is in the right range

   // And set the position

   servoPos = constrain( count * 24, 0 , 180);

   // Set the servo

   myServo.write( servoPos );
   
    // Particle.publish( "diot/2019/paired/seven12345678", "Test hahaha" );


    //motorOn = true;


}
Click to Expand

Content Rating

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

0