#include <LiquidCrystal_I2C.h>
#include <HX711.h>

#define DOUT A3
#define CLK A2

HX711 scale;

LiquidCrystal_I2C lcd(0x27, 16, 2);

#define calibration_factor 443.91

#define tare_pin 7

#define unit_pin 8

float weight;

int unit = 0;

#define gram_to_oz 0.035274

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.clear();

  Serial.begin(9600);

  scale.begin(DOUT, CLK);

  scale.set_scale(calibration_factor);

  scale.tare();

  pinMode(tare_pin, INPUT_PULLUP);

  pinMode(unit_pin, INPUT_PULLUP);

  lcd.print("Arduino Scale");
  lcd.setCursor(0, 1);
  lcd.print("By Kel.5 Kelas B");
  delay(4000);
  lcd.clear();
}

void loop() {
  weight = scale.get_units(10) * 1000;

  lcd.setCursor(0, 0);
  lcd.print("Weight: ");
  if (unit == 0) {
    lcd.print(weight, 1);
    lcd.print(" gram");
  } else {
    lcd.print(weight * gram_to_oz, 1);
    lcd.print(" oz");
  }

  Serial.print("Weight: ");
  Serial.print(weight, 1);
  Serial.println(" gram");

  if (digitalRead(tare_pin) == LOW) {
    scale.tare();
    lcd.setCursor(0, 1);
    lcd.print("Tare done!");
    delay(1000);
    lcd.clear();
  }

  if (digitalRead(unit_pin) == LOW) {
    unit = 1 - unit;
    lcd.setCursor(0, 1);
    lcd.print("Unit changed!");
    delay(1000);
    lcd.clear();
  }
}