#include <Keypad.h>
#include <Servo.h>
#include <Arduino.h>
#include "HX711.h"

const int ROWS = 4;
const int COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte pin_rows[ROW_NUM] = {3, 8, 7, 5};
byte pin_column[COLUMN_NUM] = {4, 2, 6};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

const int LOADCELL_DOUT_PIN = 11;
const int LOADCELL_SCK_PIN = 10;

HX711 scale;

Servo myservo;
int servoPin = 9;
int number;
int fraction;
bool open = false;
int pos = 0;

void setup() {
  myservo.attach(servoPin);
  Serial.begin(57600);
  myservo.write(pos);
  
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(-13.7775); // Adjust the scale calibration value
  
  scale.tare(); // Set the scale to zero
  
  Serial.println("Scale is ready!");
}

void loop() {
  char key = keypad.getKey();
  
  if (key != NO_KEY) {
    if (key >= '0' && key <= '9') {
      number = (number * 10) + (key - '0');
      Serial.println(number);
    }
    else if (key == '*') {
      number = 0;
      open = false;
      Serial.println(number);
      pos = 0;
      myservo.write(pos);
    }
    else if (key == '#') {
      open = true;
      scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
      scale.set_scale(-13.7775);
      scale.tare(5);
      delay(1000);
    }
  }
  
  if (open) {
    pos = 80;
    myservo.write(pos);
    Serial.println("Opened");
    Serial.println(number);
    fraction = (number/100*90);
    Serial.println(fraction);
    delay(50);
    long scaleReading = scale.get_units(10); // Adjust the number of readings for average if needed
    Serial.println(scaleReading);

    if (scaleReading >= (fraction)) { // if at 90% of number
      open = false;
      for (pos = 90; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      Serial.println("Closed");
      number = 0;
    }
    else if (scaleReading <= (fraction)) {
      open = true;
    }
      if (key != NO_KEY) {
        if (key == '*'){
          number = 0;
          pos = 0;
          myservo.write(pos);
          Serial.println(pos);
          Serial.println("Closed");
          delay(500);
          open = false;
        }
      }
    }
  
  delay(20);
}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
keypad1:R1
keypad1:R2
keypad1:R3
keypad1:R4
keypad1:C1
keypad1:C2
keypad1:C3
keypad1:C4
servo1:GND
servo1:V+
servo1:PWM
cell1:VCC
cell1:DT
cell1:SCK
cell1:GND