#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "HX711.h"
LiquidCrystal_I2C lcd(0x27, 20, 4);
HX711 scale;
const int loadCellDoutPin = 27;
const int loadCellSckPin = 26;
const int tareButtonPin = 13;
const int ledTambahanPin = 2; // LED untuk indikasi berat stabil
long tareWeight = 0;
float scaleFactor = 1.0;
float currentWeight = 0.0;
bool isTared = false;
const int numSamples = 10;
const float minWeightChange = 0.1;
// Weight category thresholds
const float categoryThresholds[] = {1500, 2000, 2500, 3000};
enum WeightCategory {
NoCategory,
Category1,
Category2,
Category3,
Category4
};
void setup() {
pinMode(ledTambahanPin, OUTPUT); // Set LED tambahan as output
Serial.begin(9600);
lcd.init();
lcd.backlight();
scale.begin(loadCellDoutPin, loadCellSckPin);
scale.set_scale();
scale.tare();
pinMode(tareButtonPin, INPUT_PULLUP);
initializeDisplay();
}
void loop() {
float newWeight = getStableWeight();
if (abs(newWeight - currentWeight) > minWeightChange) {
currentWeight = newWeight;
displayWeightAndCategory(currentWeight);
digitalWrite(ledTambahanPin, LOW); // Matikan LED tambahan saat berat terbaca
} else {
digitalWrite(ledTambahanPin, HIGH); // Hidupkan LED tambahan saat berat stabil
}
if (digitalRead(tareButtonPin) == LOW) {
if (isTared) {
isTared = false;
currentWeight = -currentWeight;
displayWeightAndCategory(currentWeight);
}
showFeedback("Tare Berhasil!", 1000);
}
}
long calculateTare() {
long totalTare = 0;
for (int i = 0; i < numSamples; i++) {
totalTare += scale.get_units();
delay(100);
}
return totalTare / numSamples;
}
float getStableWeight() {
float totalWeight = 0.0;
for (int i = 0; i < numSamples; i++) {
totalWeight += getWeight();
delay(100);
}
return totalWeight / numSamples;
}
float getWeight() {
float rawWeight = scale.get_units() * 2.381;
return (rawWeight - tareWeight) * scaleFactor;
}
void initializeDisplay() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" RPA NUSANTARA ");
lcd.setCursor(0, 1);
lcd.print("Berat: ");
lcd.setCursor(0, 2);
lcd.print("Kategori: ");
}
void displayWeightAndCategory(float weight) {
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print("Berat: ");
lcd.print(weight);
WeightCategory category = determineWeightCategory(weight);
lcd.setCursor(10, 2);
lcd.print(category);
}
WeightCategory determineWeightCategory(float weight) {
for (int i = Category1; i <= Category4; i++) {
if (weight <= categoryThresholds[i - 1]) {
return static_cast<WeightCategory>(i);
}
}
return NoCategory;
}
void showFeedback(const char* message, unsigned long duration) {
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(message);
delay(duration);
lcd.setCursor(0, 1);
lcd.print(" ");
}