#include <Servo.h>
#include <HX711.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define trigger 10
#define echo 11
#define maxdist 100
#define servo 9
#define relay 8
#define dt A0
#define sck A1
Servo myservo;
HX711 scale;
LiquidCrystal_I2C lcd(0x27, 16, 2);
unsigned long lastLargeDetectionTime = 0;
unsigned long lastSmallDetectionTime = 0;
int largeBagCount = 0;
int smallBagCount = 0;
bool systemHalted = false;
void setup() {
Serial.begin(9600);
myservo.attach(servo);
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
scale.begin(dt, sck);
scale.set_scale(420.0983); // Load cell calibration factor
lcd.init();
lcd.backlight();
lcd.print("System Ready");
}
long getDistance() {
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
long duration = pulseIn(echo, HIGH);
return duration * 0.034 / 2; // Convert to distance in cm
}
void loop() {
if (systemHalted) {
lcd.clear();
lcd.print("HALT!");
lcd.setCursor(0, 1);
lcd.print("OVERLOAD!");
return;
}
int distance = getDistance();
float weight = scale.get_units(5);
if (distance > 0 && distance <= maxdist) {
if (weight > 23 && weight < 27) { // Large bag (25 kg with some tolerance)
largeBagCount++;
lastLargeDetectionTime = millis();
Serial.println("Large bag");
if (largeBagCount > 2 && (millis() - lastLargeDetectionTime) <= 10000) {
systemHalted = true;
digitalWrite(relay, LOW); // Stop the conveyor
Serial.println("System halted: Overload!");
}
} else if (weight > 8 && weight < 12) { // Small bag (10 kg with some tolerance)
smallBagCount++;
lastSmallDetectionTime = millis();
Serial.println("Small bag");
if (smallBagCount > 2 && (millis() - lastSmallDetectionTime) <= 6000) {
systemHalted = true;
digitalWrite(relay, LOW); // Stop the conveyor
Serial.println("System halted: Overload!");
}
}
// Remove the bag from the line
myservo.write(90);
delay(1000);
myservo.write(0);
}
// Reset counters if time window has passed
if (millis() - lastLargeDetectionTime > 10000) largeBagCount = 0;
if (millis() - lastSmallDetectionTime > 6000) smallBagCount = 0;
// Update LCD
lcd.clear();
lcd.print("L:");
lcd.print(largeBagCount);
lcd.print(" S:");
lcd.print(smallBagCount);
lcd.setCursor(0, 1);
lcd.print("Dist:");
lcd.print(distance);
lcd.print("cm");
delay(100); // Short delay for stability
}