#include "HX711.h"
HX711 scale;
float scale_offset = 8384633;
float calibration_factor = -14.7;
float GRAM;
bool locked = false;
static unsigned long previousMillis = 0;
static long previousWeight = 0;
static bool isStable = false;
unsigned long currentMillis ;
long weightDiff;
float mem_gram = 0;
void setup() {
Serial.begin(115200);
scale.begin(2, 4);
scale.set_offset(scale_offset);
scale.set_scale();
long zero_factor = scale.read_average();
Serial.print("Zero factor: ");
Serial.println(zero_factor);
}
void loop() {
scale.set_scale(calibration_factor);
GRAM = scale.get_units(), 4;
if (GRAM < 1000)
{
GRAM = 0;
}
if ((!locked) && (GRAM > 10000))
{
locked = true;
}
if (GRAM < 10000)
{
locked = false;
}
mem_gram = GRAM;
isStable = false;
currentMillis = millis();
if (currentMillis - previousMillis >= 2000)
{
mem_gram = scale.get_units(), 4;
if (mem_gram > 10000)
Serial.println(mem_gram / 1000);
previousMillis = currentMillis;
weightDiff = abs(mem_gram - previousWeight);
previousWeight = mem_gram;
if (weightDiff <= 500)
isStable = true;
else
isStable = false;
if (weightDiff <= 500 && isStable)
{
if (locked)
{
if (mem_gram > 100000)
{
float kg = mem_gram / 1000;
String payload = String(kg, 2) ;
Serial.println(payload);
while (locked)
{
GRAM = scale.get_units(), 4;
if (GRAM < 10000)
{
locked = false;
Serial.println("0.0");
}
}
}
else
{
float kg = mem_gram / 1000;
String payload = String(kg, 2) ;
Serial.println(payload);
while (locked)
{
GRAM = scale.get_units(), 4;
if (GRAM < 10000)
{
locked = false;
Serial.println("0.0");
}
}
}
}
}
}
}