#include "HX711.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Replace with actual reset pin if used
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Define the HX711 load cell pins
#define DOUT 2
#define CLK 3
HX711 scale;
// Variables to keep track of the bags
unsigned long lastLargeBagTime = 0;
unsigned long lastSmallBagTime = 0;
int largeBagCount = 0;
int smallBagCount = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Initialize OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
delay(2000); // Pause for 2 seconds
display.clearDisplay();
display.setTextColor(SSD1306_WHITE);
scale.begin(DOUT, CLK);
}
void loop() {
// Read the current time
unsigned long currentTime = millis();
if (scale.is_ready()) {
// Read the weight value
float weight = scale.get_units();
weight *= 2.381;
// Determine the type of bag based on weight ranges
bool isLargeBag = (weight >= 20000 && weight <= 22000); // 20-22 kg range
bool isSmallBag = (weight >= 10000 && weight <= 12000); // 10-12 kg range
// Update bag counts and time stamps
if (isLargeBag) {
if (currentTime - lastLargeBagTime <= 10000) { // 10 seconds window
largeBagCount++;
} else {
largeBagCount = 1;
}
lastLargeBagTime = currentTime;
} else if (isSmallBag) {
if (currentTime - lastSmallBagTime <= 6000) { // 6 seconds window
smallBagCount++;
} else {
smallBagCount = 1;
}
lastSmallBagTime = currentTime;
}
// Check for overloading condition
if (largeBagCount > 2 || smallBagCount > 2) {
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("System Halted");
display.setCursor(0, 10);
display.println("Overload detected");
display.display();
while (1) { // Halt the system
delay(1000);
}
}
// Print the weight in kilograms and bag counts on the OLED display
display.clearDisplay();
display.setTextSize(1); // Set text size to 1
display.setCursor(0, 0); // Set cursor to the first line
display.print("Weight: ");
display.print(weight / 1000, 1); // Print kilograms with 1 decimal place
display.println(" kg");
display.setCursor(0, 10); // Move to the next line
display.print("Large bags: ");
display.println(largeBagCount);
display.setCursor(0, 20); // Move to the next line
display.print("Small bags: ");
display.println(smallBagCount);
display.display();
delay(1000); // Wait for a second before taking another reading
} else {
display.clearDisplay();
display.setTextSize(1);
display.setCursor(0, 0);
display.println("Error: Unable to detect HX711.");
display.setTextSize(1);
display.setCursor(0, 10);
display.println("Please check your connections.");
display.display();
delay(1000);
}
}