How do I set a continuous servo to turn on until a switch is flicked? I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:



Here is my code:

#include &lt;Servo.h&gt;
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}


Any help would be appreciated.
Your are not debouncing your input buttons, which means that digitalRead(Closed) (and Open) will be HIGH in one execution of loop and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know? 

Usually the first step when you find a problem is add Serial.print to know what is working and what not, and then correct the problem.