2 buttons, 1 servo, turn when pressed only I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.

The problem is that my code is fine on startup, but when i press the button the servo continues to spin.

How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?

#include &lt;Servo.h&gt;

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW =&gt; clockwise =&gt; FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC =&gt; counterclockwise =&gt; FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  } 
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}
If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your loop as a if expression where you check if both buttons read LOW:

void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  } 
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed? 
  if(buttonStateCC == LOW &amp;&amp; buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}


This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as 0 and a pressed on reads as 1 (HIGH). This is unusual because we usually use the internal pullup resistors via the INPUT_PULLUP pinMode parameter with a switched logic (1 = unpressed, 0 = pressed).

I've also removed the line crServo = digitalRead(crSpeedDefault); because that doesn't make sense in my opinion, as I've detailed in my comment.