#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "HX711.h"
// Pin Definitions
#define DT 4
#define SCK 5
#define TARE_BUTTON 12
#define PLUS_BUTTON 13
#define MINUS_BUTTON 14
#define START_BUTTON 27
#define OFF_BUTTON 26
#define RELAY_PIN 23
// LCD Settings
LiquidCrystal_I2C lcd(0x27, 16, 2);
// HX711 Settings
HX711 scale;
float targetWeight = 20.0; // Default target weight in grams
bool relayState = false;
void setup() {
Serial.begin(115200);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Initializing...");
// Initialize HX711
scale.begin(DT, SCK);
scale.set_scale(); // Calibrate scale here
scale.tare(); // Reset scale to 0
// Set up pins
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW);
pinMode(TARE_BUTTON, INPUT_PULLUP);
pinMode(PLUS_BUTTON, INPUT_PULLUP);
pinMode(MINUS_BUTTON, INPUT_PULLUP);
pinMode(START_BUTTON, INPUT_PULLUP);
pinMode(OFF_BUTTON, INPUT_PULLUP);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Target: ");
lcd.print(targetWeight, 2);
}
void loop() {
float weight = scale.get_units();
// Tare button
if (digitalRead(TARE_BUTTON) == LOW) {
scale.tare();
updateDisplay();
delay(300);
}
// Adjust target weight
if (digitalRead(PLUS_BUTTON) == LOW) {
targetWeight += 0.50;
updateDisplay();
delay(300);
}
if (digitalRead(MINUS_BUTTON) == LOW) {
targetWeight -= 0.50;
if (targetWeight < 0) targetWeight = 0;
updateDisplay();
delay(300);
}
// Start button
if (digitalRead(START_BUTTON) == LOW) {
relayState = true;
digitalWrite(RELAY_PIN, HIGH);
updateDisplay();
delay(300);
}
// Turn off button
if (digitalRead(OFF_BUTTON) == LOW) {
relayState = false;
digitalWrite(RELAY_PIN, LOW);
updateDisplay();
delay(300);
}
// Check weight and auto-off relay
if (relayState && weight >= targetWeight) {
relayState = false;
digitalWrite(RELAY_PIN, LOW);
updateDisplay();
}
}
void updateDisplay() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Target: ");
lcd.print(targetWeight, 2);
lcd.print("g");
lcd.setCursor(0, 1);
lcd.print("Weight: ");
lcd.print(scale.get_units(), 2);
if (relayState) {
lcd.print(" ON");
} else {
lcd.print(" OFF");
}
}