#include <HX711_ADC.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

HX711_ADC LoadCell(4, 5);               // DT, SCK pins
LiquidCrystal_I2C lcd(0x27, 16, 2);     // LCD I2C address, 16x2

int taree = 6;                          // Tare button pin
float lastWeight = -9999;              // To force update at first
unsigned long lastUpdate = 0;

void setup() {
  pinMode(taree, INPUT_PULLUP);

  LoadCell.begin();
  LoadCell.start(1000);
  LoadCell.setCalFactor(-375);         // Use negative if weights showed negative

  lcd.init();
  lcd.backlight();

  // Intro Scroll
  String intro = "letsmakeprojects.com";
  for (int i = 0; i <= intro.length() - 16; i++) {
    lcd.setCursor(0, 0);
    lcd.print(intro.substring(i, i + 16));
    delay(250);
  }

  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print("Digital Scale ");
  lcd.setCursor(0, 1);
  lcd.print(" Place Object ");
  delay(3000);
  lcd.clear();
}

void loop() {
  LoadCell.update();
  float weight = LoadCell.getData();

  // Auto-zero for minor noise
  if (abs(weight) < 1.0) weight = 0.0;

  // Only update if weight changed significantly
  if (abs(weight - lastWeight) > 0.1 || millis() - lastUpdate > 2000) {
    lastUpdate = millis();
    lastWeight = weight;

    // Line 0 – Static label
    lcd.setCursor(0, 0);
    lcd.print("Weight:         ");  // fixed label with spaces to avoid leftovers

    // Line 1 – Weight and ounces
    lcd.setCursor(0, 1);
    lcd.print("                "); // Clear the full row once

    lcd.setCursor(1, 1);
    lcd.print(weight, 1);
    lcd.print("g ");

    float oz = weight / 28.3495;
    lcd.setCursor(9, 1);
    lcd.print(oz, 2);
    lcd.print("oz");
  }

  // Overload check
  if (weight >= 5000) {
    lcd.setCursor(0, 0);
    lcd.print("  Over Loaded   ");
    delay(500); // pause to show warning
  }

  // Tare function
  if (digitalRead(taree) == LOW) {
    lcd.setCursor(0, 1);
    lcd.print("   Taring...    ");
    LoadCell.start(1000);
    lcd.setCursor(0, 1);
    lcd.print("                ");
    lastWeight = -9999;  // force next update
  }
}
