/*
  Wokwi | general
  GO YOON JUNG — 6/18/24 at 11:11 PM

  Instructions: Make a program and circuit based on
  the conditions in the following problem!

  A system controlled by Arduino Uno has input in the
  form of 2 pushbottons (PB1 and PB2) and a servo motor
  output in the normal position and an LCD. Works as follows:

  When PB1 is pressed, the LCD will display the word "OPEN"
  and the servo motor will rotate +90°

  When PB2 is pressed, the servo motor will return to its
  original position (normal) and the LCD will displays the
  word "CLOSED"

  PB1 is connected to pin 0 and PB2 is connected to pin 5.
          ^^^^^^^ Don't use pin 0 ^^^^^^^^
*/

#include <LiquidCrystal_I2C.h>
#include <Servo.h>

const int NUM_BUTTONS = 2;
const int BTN_PINS[NUM_BUTTONS] = {8, 7};
const int SERVO_PIN = 2;

int btnStates[NUM_BUTTONS];
int oldBtnStates[NUM_BUTTONS];

LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo servo;

int checkButtons(int btnNum) {
  int retVal = -1;
  btnStates[btnNum] = digitalRead(BTN_PINS[btnNum]);
  if (btnStates[btnNum] != oldBtnStates[btnNum])  {
    oldBtnStates[btnNum] = btnStates[btnNum];
    if (btnStates[btnNum] == LOW) {
      //Serial.print("Button ");
      //Serial.print(btnNum);
      //Serial.println(" pressed.");
      retVal = btnNum;
    }
    delay(20);  // debounce
  }
  return retVal;
}

void controlGate(int value) {
  lcd.clear();
  switch (value)  {
    case 0:
      servo.write(90);
      lcd.setCursor(6, 0);
      lcd.print("OPEN");
      Serial.println("Gate open pressed");
      break;
    case 1:
      servo.write(180);
      lcd.setCursor(5, 1);
      lcd.print("CLOSED");
      Serial.println("Gate close pressed");
      break;
    default:
      break;
  }
}

void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  pinMode(BTN_PINS[0], INPUT_PULLUP);
  pinMode(BTN_PINS[1], INPUT_PULLUP);
  servo.attach(SERVO_PIN);
  // splash screen
  lcd.setCursor(6, 0);
  lcd.print("Gate");
  lcd.setCursor(3, 1);
  lcd.print("Controller");
  delay(2000);
  // initialize
  servo.write(180);
  lcd.clear();
  lcd.setCursor(5, 1);
  lcd.print("CLOSED");
  Serial.println("Gate starts closed\n");
}

void loop() {
  for (int i = 0; i < NUM_BUTTONS; i++) {
    int pressedBtn = checkButtons(i);
    if (pressedBtn >= 0)  {
      controlGate(pressedBtn);
    }
  }
}
$abcdeabcde151015202530fghijfghij