use servo "detach" with servo knob example

I am wondering if it's possible to implement the "detach" command in the simple "servo knob" tutorial. I want to be able to detach the servo from the pin after +/- 1/2 sec and attach again as soon as I move the pot to change the position of the servo and then detach again. Can someone show me how this can be accomplished using the servo knob example? After seeing how it's done I may be able to incorporate into my code and give it a try. This will save battery power and keep the cheaper servos from humming. I'm just learning code and hope this will work for my first project.


I’d try something like this:

// Controlling a servo position using a potentiometer (variable resistor) 
// by Michal Rinott <> 

#include <Servo.h> 
Servo myservo;  // create servo object to control a servo 
const int potpin = A0;  // analog pin used to connect the potentiometer
const int servoPin = 9; 

int lastVal = 0;    // variable to read the value from the analog pin 
unsigned long timeOfLastChange = 0;
void setup() 
void loop() 
  int val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023) 
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180) 
  if (val != lastVal)
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
    myservo.write(val);                  // sets the servo position according to the scaled value 
    delay(15);                           // waits for the servo to get there 
    timeOfLastChange = millis();
    lastVal = val;
  else if (millis() - timeOfLastChange > 500)

Thanks John, I'll give this a try.

Hi John,

I loaded this sketch and it never detached. Worked the same as the sample knob sketch. Any thoughts?


Perhaps your analog input is not staying stable for a full 1/2 second. You could try putting in error bands:

  if (val < (lastVal-5) || val > (lastVal+5))

Your servo won’t respond to small knob changes but it should detach more readily.

Thanks John, this worked out perfect. I was able to narrow the dead-band to 2 and it detaches fine. The wider dead-band causes the servo to be a bit more jumpy when first starting. Made a few adjustments to the code and it's working great. Thank you for the help.

Thanks for sharing! :D