#include <Arduino.h>
#include "HX711.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 0;
HX711 scale;
void calibrateScale();
// Known weight in grams for calibration
const float knownWeight = 5000; // Change this to your known weight
void setup() {
Serial.begin(115200);
while (!Serial) {
; // Wait for serial port to connect
}
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(0.424);
calibrateScale();
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 10);
// Display static text
display.println("Testing");
display.display();
}
void loop() {
if (scale.is_ready()) {
long reading = scale.get_units();
Serial.print("HX711 reading: ");
Serial.println(reading);
display.clearDisplay();
display.setCursor(0, 10);
// Display static text
display.print("Reading : ");
display.println(reading);
display.display();
} else {
Serial.println("HX711 not found.");
}
}
// Calibration function
void calibrateScale() {
float scaleFactor = 1.0; // Initial scale factor
// Set up the scale
scale.set_scale();
// Tare the scale to zero
scale.tare();
// Place the known weight on the scale and measure it
Serial.println("Place the known weight on the scale.");
while (Serial.peek() != '\n');
float measuredWeight = scale.get_units(10); // Read the weight
Serial.print("Measured weight: ");
Serial.print(measuredWeight);
Serial.println(" g");
// Calculate the scale factor
scaleFactor = measuredWeight / knownWeight;
// Apply the scale factor to the HX711 instance
scale.set_scale(scaleFactor);
// Print the calibration factor for reference
Serial.print("Calibration factor: ");
Serial.println(scaleFactor);
}