0

Why my servo motor is always on?

Schematic

#include <Servo.h> 

Servo myservo;

int pos = 0;

void setup() {

pinMode(2, INPUT);
myservo.attach(9);

}

void loop() {

  if (digitalRead(2) == LOW) {

    for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(15);
    }

    for (pos = 180; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(15);
    }
  }
  else {
    myservo.write(0);
    delay(15);
  }
}

migrated from electronics.stackexchange.com May 7 at 20:25

This question came from our site for electronics and electrical engineering professionals, students, and enthusiasts.

  • 4
    Provide a proper schematic and listing. – Leon Heller May 7 at 16:19
  • 3
    What do you mean by 'always on', is it always moving or always energized? – Jack Creasey May 7 at 16:24
  • 4
    @TimWescott Why not simply give the OP the opportunity to alter the question rather than hastily 'close' the question. Once closed it seems unlikely to get votes to open again even if it is altered. This is really just 'close' being used as a form of bullying. – Jack Creasey May 7 at 16:29
  • 5
    @JackCreasey I did not invent Stackexchange, or its rules. I just follow them. As was pointed out to me when I asked just your question, closed questions do get reopened when they are fixed up. – TimWescott May 7 at 16:32
  • 2
    Closing would prevent a bunch of well-intended but poorly informed (no info from OP) answers to be written and made obsolete by updates on the question and context. – Wesley Lee May 7 at 16:38
1

It looks like you need to enable the pull-up resistor on D2. As written D2 is left floating and most likely is a low voltage relative to ground. Enabling the pull up resistor will force the pin high until you flip the switch.

  • Arduino inputs have significant capacitance. So once the switch has been pressed the input will tend to stay low. Use either pinMode(pin, INPUT_PULLUP) or use digitalWrite(pin, HIGH) to turn on the pullup for a (pin) configured as INPUT. – Jack Creasey May 7 at 19:02
  • it works!! thanks – Anont Lamache May 7 at 20:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.