/*
Arduino code - Code is used to: 
* control servo motor with push button
* display LED at all times
* display LCD at servo's initial position
*/

// introduce servo motor and LCD
#include <Servo.h>
#include <LiquidCrystal.h>

Servo Servo1;
LiquidCrystal lcd(12,11,5,4,3,2);

// global variables
const int buttonPin =  6;

boolean currentState = LOW;
boolean lastState    = LOW;
boolean stateChange  = false;

int currentButton = 0;
int lastButton    = 1;
int pos = 0;
int led = 13;

// setup button, sevo, LED, and LCD
void setup() {
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  Servo1.attach(9);
  while (pos==lastButton);{
    pinMode(led, OUTPUT);
   lcd.begin(16, 2);
   lcd.clear();
} 
}

// main loop
// call functions and keep LED on at all times
void loop(){
  currentState = debounceButton();
  stateChange = checkForChange(currentState, lastState);
  currentButton = getButtonNumber(lastButton, currentState, stateChange);
  servoControl(currentButton);
  lastState  = currentState;
  lastButton = currentButton;
  digitalWrite(led, HIGH);
  printfunction(currentButton);
}

// function debounceButton
boolean debounceButton()
{
  boolean firstCheck   = LOW;
  boolean secondCheck  = LOW;
  boolean current = LOW;  
  firstCheck  = digitalRead(buttonPin);
  delay(50);
  secondCheck = digitalRead(buttonPin);  
  if (firstCheck == secondCheck){
    current = firstCheck;
  }
  return current;
}

// function checkForChange
boolean checkForChange(boolean current, boolean last)
{
  boolean change;  
  if (current != last){
    change = true;
  }
  else {
  change = false;
  }  
  return change;
}
      
// function getButtonNumber
int getButtonNumber(int button, boolean state, boolean change)
{
  if (change == true && state == LOW){
    button++;
    if (button > 1){
      button = 0;
    }
    Serial.println(button);
  }
  return button;
}

// function servoControl
// base servo position off of button state
// make sure that first position is intended initial position
void servoControl(int button)
{
  if(button == 1) {Servo1.write(160);}
  if(button == 0) {Servo1.write(70);}
}

// function printfunction
// base LCD display off of button state
void printfunction (int button)
{
  if(button == 1) {
  lcd.setCursor(0,0);
  lcd.print ("!!!! RELOAD !!!!!");
}
  else{lcd.clear();
}
}