Pushbutton to toggle between units (ounces and grams) with HX711 and LCD screen

Take this for a spin and see how it works for you. It should update the LCD twice a second (every 500 milliseconds), I set the update frequency (READ_FREQUENCY_MS) at the top. The faster you let it update the more the screen will flicker, then again slow updates aren't helpful on a 'live' scale so you might need to find a balance.

#include "HX711.h"

#include "KTS_Button.h"

#define READ_FREQUENCY_MS 500

#define DOUT  8
#define CLK  7

#define unitsPin 6 //Units button at pin 6

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int tarePin = 9;  //Tare button at pin 9
float tareVal = 0;
float i = 0;

HX711 scale;

float calibration_factor = 360; //calibration factor for 5kg amazon load cell with gain 128 and grams as units

KTS_Button tareButton(tarePin);
KTS_Button unitsButton(unitsPin);

enum Unit {
  grams = 0,
  ounces,
  NUM_UNITS
}; Unit currentUnit = grams;

void cycleUnits() {
  currentUnit = currentUnit + 1;
  if (currentUnit == NUM_UNITS)
    currentUnit = 0;
}

void setup() {
  pinMode(SCK, OUTPUT);
  pinMode(tarePin, INPUT_PULLUP);
  lcd.begin(16, 2);
  scale.begin(DOUT, CLK, 128); //Start communications to HX711 pins and set gain factor 64|128 are options on Channel A
  scale.set_scale(calibration_factor);           //Required during scale startup, scale factor will be adjusted in main loop for calibration
  scale.tare();                //Reset the scale to 0
}

void loop() {
  if (tareButton.read() == SINGLE_PRESS) {
    lcd.clear();
    lcd.print("Tare");
    delay(1000);
    scale.tare();
  }

  if (unitsButton.read() == SINGLE_PRESS) {
    cycleUnits();
  }

  static uint32_t timeCapture;

  if ((millis() - timeCapture) > READ_FREQUENCY_MS) {
    timeCapture = millis();
    
    lcd.clear();
    lcd.print("Weight: ");
    lcd.setCursor(0,1);

    switch (currentUnit) {
      case grams:
        lcd.print(scale.get_units (4), 1);
        lcd.print("g");
        break;
      case ounces:
        lcd.print(scale.get_units (4) * 0.03524, 1);
        lcd.print("oz");
        break;
    }
  }
}
1 Like