#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "HX711.h"
#define DOUT_PIN 2 // HX711 data pin
#define CLK_PIN 3 // HX711 clock pin
#define WEIGHT_THRESHOLD 100 // Adjust this threshold according to your setup
#define COUNT_BUTTON_PIN 4 // Pin for count button
#define TARE_BUTTON_PIN 5 // Pin for tare button
#define SET_SEED_BUTTON_PIN 6 // Pin for setting seed value
HX711 scale;
// Define calibration factor (replace this with your own calibration factor)
const float calibration_factor = 419.94;
// Define I2C address for the LCD
const int i2c_address = 0x27; // Change this address if your I2C backpack has a different address
// Define LCD dimensions (typically 16x2)
const int lcd_columns = 16;
const int lcd_rows = 2;
// Initialize LCD object
LiquidCrystal_I2C lcd(i2c_address, lcd_columns, lcd_rows);
// Define variables for counting
float seed_value = 0; // Weight of a single item
bool seed_set = false; // Flag to indicate if seed value is set
int object_count = 0; // Count of objects placed on scale
void setup() {
Serial.begin(9600);
lcd.begin(lcd_columns, lcd_rows);
scale.begin(DOUT_PIN, CLK_PIN);
scale.set_scale(calibration_factor);
lcd.print("Press set seed");
// Initialize button pins
pinMode(COUNT_BUTTON_PIN, INPUT_PULLUP);
pinMode(TARE_BUTTON_PIN, INPUT_PULLUP);
pinMode(SET_SEED_BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// Read the weight from the scale
float weight = scale.get_units();
// Check if seed value needs to be set
if (!seed_set) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Press set seed");
if (digitalRead(SET_SEED_BUTTON_PIN) == LOW) {
seed_value = weight;
seed_set = true;
lcd.clear();
lcd.print("Seed set");
delay(1000); // Display message for 1 second
}
} else {
// Counting mode
lcd.clear();
lcd.print("Counting...");
if (weight >= seed_value && weight < seed_value * 2) {
object_count++;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Object count: ");
lcd.print(object_count);
Serial.print("Object count: ");
Serial.println(object_count);
delay(500); // Debounce delay
}
}
// Check tare button press
if (digitalRead(TARE_BUTTON_PIN) == LOW) {
scale.tare(); // Tare the scale
lcd.clear();
lcd.print("Tare performed");
delay(1000); // Display message for 1 second
lcd.clear();
lcd.print("Press set seed");
}
// Print the weight on the LCD
lcd.setCursor(0, 1);
lcd.print("Weight: ");
lcd.print(weight);
lcd.print(" g");
delay(100); // Add a small delay for stability
}