Bummer...Failed to call

Hello everyone,

I’m having trouble getting my particle function to run. I assume that I am missing some bit of knowledge about how the code works when a function is called. I’m running a servo motor that should move 45 degrees when the command “open” or “close” is typed into the console. Can anyone see what I am missing?

Not sure how to embed the code but here it is:

Servo elvinServo;

void setup() {
  elvinServo.attach(D0);

  Particle.function("Open Door", openDoor);
  Particle.function("Close Door", closeDoor);
}

void loop() {
}

int openDoor(String command) {
  if( command == "open") {
    for(int angle = 0; angle < 45; angle += 1)    // command to move from 0 degrees to 180 degrees in increments of 1
    {
      elvinServo.write(angle);                 //command to rotate the servo to the specified angle
    }
   
    return 1;
  }
  else {
    return -1;
  }
}

int closeDoor(String command) {
  if(command == "close") {
    for(int angle = 45; angle >= 1; angle -= 1)   
    {
      elvinServo.write(angle);             
    }
    
    return 1;
  }
  else {
    return -1;
  }
}

should be easier…

Servo elvinServo;

void setup() {
  elvinServo.attach(D0);
  Particle.function("Door", door);
}

void loop() {

}

int door(String command) {
  if ( command == "open") {
    elvinServo.write(90);
    return 90;
  }
  else if ( command == "close") {
    elvinServo.write(0);
    return 0;
  }
  return -1;  //error
}
1 Like

Hey there @KID_Museum thanks for posting. I went ahead and formatted your code sample, but you can check out this thread for info on how to do it for future posts.

Brandon

1 Like

Thanks @bsatrom , I appreciate the hand.

and thanks @BulldogLowell I’ll try that.

Totally worked! but what was wrong with my code? I know it was more complicated but what was the actual problem?

I really don’t know what your intention was in those for-loops, that made little sense to me. Particle Functions should really be very minimal code, much like interrupt handling.

If you want to sweep the servo more slowly towards its target, you can develop a class to implement that in loop, like this example I did for you.

I’d say the problem with your code was not the Particle.function() itself but the way how you applied the servo.write() in that for() loop which would only take some hundred microseconds from elvinServo.write(start) to elvinServo.write(end).
No need to “ramp” the angle.

Also we don’t really know how you actually called the function remotely.
Also what were the return values you got from the calls?

2 Likes