int servoPin = A5;
int servoPosition = 0;
Servo servo;
void setup()
{
Serial.begin( 9600 );
Particle.function( "pos", setPosition );
servo.attach( servoPin );
}
void loop()
{
delay(100);
}
int setPosition(String command) {
Serial.println("setSpeed: " + command);
int value = command.toInt();
if (value < 0) return -1;
if (value > 180) return -1;
int targetPosition = constrain(value, 0, 180);
// Gradually move to the new position
while (servoPosition != targetPosition) {
if (servoPosition < targetPosition) {
servoPosition++; // Increment position
} else if (servoPosition > targetPosition) {
servoPosition--; // Decrement position
}
servo.write(servoPosition); // Update servo position
delay(20); // Adjust delay to control speed (lower = faster, higher = slower)
}
return 1;
}
Click to Expand