#define VERT_PIN A0
#define HORZ_PIN A1

#include <Servo.h>

Servo leftServo;  // create servo object to control a servo
Servo rightServo;

int leftPos = 0;    // variable to store the servo position
int rightPos = 0;
  
bool buttonPressed = false;
bool leftServoOn = false;
bool rightServoOn = false;
bool interrupted = false;

void setup() {
  pinMode(VERT_PIN, INPUT);
  pinMode(HORZ_PIN, INPUT);

  // attach to pins suitable for PWM waves
  leftServo.attach(3);
  rightServo.attach(6);
}

// creates signal via buttonPressed and the appropriate button
void detectPad() {
  int vert = analogRead(VERT_PIN);
  int horz = analogRead(HORZ_PIN);

  if (horz == 1023 && vert == 512) {
    //left
    // servo1
    buttonPressed = true; 
    leftServoOn = true;
  }

  if (horz == 0 && vert == 512) {
    // right
    // servo1
    buttonPressed = true; 
    rightServoOn = true;
  }
}

void loop() {

  // get initial instruction
  // if interrupted (button pressed in middle of loop - received signal, don't need to detect again)
  if (!interrupted) {
    detectPad();
  }
  else {
    // process interrupted signal - buttonPressed must be true
    interrupted = false;
  }

  if (buttonPressed && leftServoOn) {
    // top
    // move servo1 counter

    // consume signal
    buttonPressed = false;
    leftServoOn = false;


    for (leftPos = 0; leftPos <= 180; leftPos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      leftServo.write(leftPos);              // tell servo to go to position in variable 'pos'
      delay(15);
      // check pad every loop to break, get new instruction
      detectPad();
      // new signal detected: interrupting this + signal on, reset servo
      if (buttonPressed) { 
        interrupted = true;
        leftPos = 180;
        leftServo.write(leftPos); 
        break; 
      }                       
    }        
  }

  else if (buttonPressed && rightServoOn) {
    // top
    // move servo1 counter

    // consume signal
    buttonPressed = false;
    rightServoOn = false;


    for (rightPos = 0; rightPos <= 180; rightPos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      rightServo.write(rightPos);              // tell servo to go to position in variable 'pos'
      delay(15);
      // check pad every loop to break, get new instruction
      detectPad();
      // new signal detected: interrupting this + signal on, reset servo
      if (buttonPressed) { 
        interrupted = true;
        rightPos = 180;
        rightServo.write(rightPos); 
        break; 
      }                       
    }        
  }
}