Servo goes to angle, then goes back?

Lacking a potentiometer to set the angles of my servos (case is limiting movements), I decided to build a function, and then just pass values, and see how far the limits are.

All is good, I pass the function, and the servo moves. But 1 mili second later, the servo goes back to the initial position?

I dont see it in the code anywhere, yet it does this persistently.

How does the servo stay in the angle passed in the function?

Here's the code. I used the function example from the docs:

// This #include statement was automatically added by the Particle IDE.
#include <HC_SR04.h>

int brewCoffee(String command);


Servo myservo;  // create servo object to control a servo 
                // a maximum of eight servo objects can be created 

int pos = 0;    // variable to store the servo position 

int distance = 0;
int percentage,heightTank, deviation;
int angle;


double cm = 0.0;

int trigPin = D4;
int echoPin = D5;

HC_SR04 rangefinder = HC_SR04(trigPin, echoPin);


void setup() 
{ 
    Serial.begin(9600);
    myservo.attach(D0);  // attaches the servo on pin 0 to the servo object 
    //pinMode(D7, OUTPUT);
    Particle.function("brew", brewCoffee);

} 


void loop() 
{ 
    //myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    cm = rangefinder.getDistanceCM();
    Serial.printf("Distance: %.2f cm\n", cm);
    angle = (int) cm;
    myservo.write(angle);
    //// Uncomment for extra experiment with Distance sensor
    //setRemoteServo(cm);
    delay(850);    
}

int brewCoffee(String command)
{
  // look for the matching argument "coffee" <-- max of 64 characters long
    int angle = atoi(command);
    myservo.write(angle);
  
    //return 1;
}

Then I call the function as:

particle call XYZ brew 90

Ideas?

In the loop function, which will be executed every 0.85 seconds because of your delay, you re-write the servo angle to the distance in CM that your rangefinder is reporting. That seems a strange thing to do, to set an angle (units in degrees) to a distance (units in centimeters). But anyway, that's the line that is reseting your servo position.

ps. careful running a servo into its limits. Some servos will protect against damage, and some will not. You could damage the electronics and/or the physical gears.

4 Likes

Aaah, coffee hasnt kicked in yet! Thank you so much for your good eyes :slight_smile:

I reused the code from a previous file. It would turn the servo depending on the distance from the ultrasonic. Makes if fun for the kids, plus you can sort of build a ramp for toy cars, that auto opens when the car is close enough :slight_smile:

2 Likes

Sounds fun!

2 Likes