/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob

 Heavily modified by Jeremy S. Cook March 2018 for use with a camera slider assembly
*/

#include <Servo.h>

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

int potpin = 6;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin
int SServo = 4; //microswitch closest to servo - when pushed == high (1)
int SServoState;
int SAway = 5; //microswitch away from servo - when pushed == high (1)
int SAwayState;
void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
  Serial.begin(9600);
  pinMode(SServo, INPUT);
  pinMode(SAway, INPUT);
}

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  SServoState = digitalRead(SServo);
  SAwayState = digitalRead(SAway);
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  if(SServoState == 0 && SAwayState == 0){
    myservo.write(val);                  // sets the servo position according to the scaled value
  }
  else if(SServoState == 1 && val < 88){
    myservo.write(val);
  }
  else if(SAwayState == 1 && val > 88){
    myservo.write(val);
  }
  else{
    myservo.write(88);
  }
  Serial.println(val);                 //499 seems to be where it no longer moves
  Serial.println(SServoState);
  Serial.println(SAwayState);
  delay(15);                           // waits for the servo to get there
}

