Stopping Servo motors

Greetings guys.

I’m trying to using a killswitch to stop servo motor from rotating when the switch turned HIGH.

this is the servo im using

How can I stop the servo from rotating at all when I press the killswitch?

#include <Servo.h>

Servo myservo;



int limitswitch = 2;

int led = 13;

void setup() {
  // put your setup code here, to run once:
  myservo.attach(9);
  pinMode(limitswitch, INPUT);
  pinMode ( led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  int switch1 = digitalRead(limitswitch);

  if (switch1 == LOW)
  {
    myservo.write(90);
    delay(5000);
    myservo.write(180);
    delay(2000);
    myservo.write(0);
    digitalWrite(led, HIGH);
  }

  if (switch1 == HIGH)
  {
    myservo.detach();
    digitalWrite(led, LOW);
  }

}

How can I stop the servo from rotating at all when I press the killswitch?

Connect the kill switch to the servo's power supply.

AWOL: Connect the kill switch to the servo's power supply.

is it possible to use command instead?

Yes, but you need to get rid of all those delay()s first.

holymarder: is it possible to use command instead?

Get rid of ALL the delay()s in your code.

Have a look at the demo Several Things at a Time which illustrates the use of millis() to manage timing and has a button and a servo working "at the same time"

...R

AWOL:
Yes, but you need to get rid of all those delay()s first.

hmm kindly explain how does removing delay helps with it. if the killswitch is hit, the servo will just stop rotating doesn’t it?

holymarder: hmm kindly explain how does removing delay helps with it. if the killswitch is hit, the servo will just stop rotating doesn't it?

It won't be monitoring the kill switch in the middle of a delay(), so it won't know it's pressed until the delay() is done.

if the killswitch is hit, the servo will just stop rotating doesn't it?

If the killswitch is wired to the servo power supply, yes, that's exactly what will happen.

What's more, it's reliable, and doesn't depend on any of your code.

AWOL: If the killswitch is wired to the servo power supply, yes, that's exactly what will happen.

What's more, it's reliable, and doesn't depend on any of your code.

well yes i understand that. just to clear my doubts, detach() is the same as placing the killswitch at the power supply yes?

but right now my code does not react to detach() because of the delay function?

just to clear my doubts, detach() is the same as placing the killswitch at the power supply yes?

No. With detach(), the servo remains powered.

but right now my code does not react to detach() because of the delay function?

Correct.