How to turn servo off after reaching position

I am trying to make a Servo move to a certain position after I press a button, wait a little bit, and then move back to the starting point, but I have a cheap servo and it makes a clicking sound when not moving, so I want to make it not powered when its at the starting position, and then become powered to move and back. I was thinking of maybe using a state change system, but I’m still new to coding and don’t know how to set one up. I copied my code below if you would like to look at it.

#include <Servo.h>

Servo myservo;
int pos = 0;
const int buttonPin = 2; // the number of the pushbutton pin

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
myservo.attach(9);
}

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

if (buttonState == HIGH) {
myservo.write(110);
delay(1500);
}
else {
myservo.write(88);
delay(100);
}
}

Buy a better servo. They are supposed to hold position when powered and don't hold any specific position when unpowered.

You might try Servo.detach() but I don't recommend it.

That looks that the servo gets Not enough Power. Is your schematic OK?

  • Servo Vcc >= 4.5 Volt
  • Servo GND at Professor GND

Sometimes servos make noise when they're at specific positions. Try changing your write() values slightly to something like 112 and 86 and see if it still makes a noise.

If it does you can try doing an attach() before every write() and a detach() after. But that will slow things down and after the detach() the servo won't be able to hold its position if there is any load on it.

Steve

How would I do servo attach and detach? When I do Servo.detach or myservo.detach I get an error message.

Firstly, you SHOULD provide the extra power source for servo motor, see how to provide extra power for servo motor

Secondly, Your code is not the best practice for the button. It MAY cause other issues, see Button FAQ: common mistake - button does NOT work as expected. - Introductory Tutorials - Arduino Forum. I also recommend using timestamp instead of delay() function, see BlinkWithoutDelay example

MajorBoi47:
When I do Servo.detach or myservo.detach I get an error message.

You would need to show your exact code and the exact error message to get help on that.

Did you use the right syntax?- don't forget the ().

Syntax

servo.detach()

Is the servo under any load?