long lastPublishedAt = 0;
int publishAfter = 10000;
int button = D2;
int servoPin = A3;
Servo myServo;
int servoPos = 0;
bool motorOn = false ;
void setup() {
myServo.attach(A3);
pinMode(button, INPUT_PULLUP);
pinMode(servoPin, OUTPUT);//set servo as the output
Particle.subscribe("diot/2021/",handleSharedEvent);
}
void loop() {
publishMyEvent(); //publish the event
if (enoughTime()) //event is ready to publish
{
for (servoPos = 0 ; servoPos<=90 ; servoPos++)
{
myServo.write(servoPos);
}
}
if(enoughTime() && motorOn)
{
for (servoPos = 90 ; servoPos<=180 ; servoPos++)
{
myServo.write(servoPos);
}
for (servoPos = 180 ; servoPos>=0 ; servoPos--)
{
myServo.write(servoPos);
}
}
delay(100); //delay a bit
}
bool enoughTime()
{
return millis() - lastPublishedAt > publishAfter;
}
void publishMyEvent()
{
if(enoughTime()){
String eventName = "diot/2021/" + System.deviceID();
if( digitalRead(button) == LOW)
{
Particle.publish(eventName, "data goes here");
}
lastPublishedAt = millis();
}
}
void handleSharedEvent(const char *event, const char *data)
{
// Let's check the event name
String eventName = String( event ); // convert to a string object
String deviceID = System.deviceID();
if( eventName.indexOf( deviceID ) != -1 ){
return;
}
else{
motorOn = true;
}
}
Click to Expand