
#include <Arduino.h>
#include "HX711.h"
#include "soc/rtc.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>    //https://github.com/johnrickman/LiquidCrystal_I2C
#include <Pushbutton.h> //Pushbutton by Pololu

// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 16;
const int LOADCELL_SCK_PIN = 4;

HX711 scale;
int reading;
int lastReading;
#define CALIBRATION_FACTOR 388.9

LiquidCrystal_I2C lcd(0x27, 16, 2); 

//Button
#define BUTTON_PIN 19
Pushbutton button(BUTTON_PIN);

void setup() {

  Wire.begin(21, 22);  // SDA = 21, SCL = 22 (pins par défaut du LCD sur un ESP32)

  lcd.init();
  lcd.backlight();
  lcd.clear();

  Serial.begin(115200);
  
  rtc_cpu_freq_config_t config;
  rtc_clk_cpu_freq_get_config(&config);
  rtc_clk_cpu_freq_mhz_to_config(RTC_XTAL_FREQ_40M, &config);
  rtc_clk_cpu_freq_set_config_fast(&config);

  delay(2000);
  
  Serial.println("Initializing the scale");
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);

  scale.set_scale(CALIBRATION_FACTOR);   // this value is obtained by calibrating the scale with known weights; see the README for details
  scale.tare();               // reset the scale to 0
}

void loop() {
  if (button.getSingleDebouncedPress()){
    Serial.print("tare...");
    lcd.setCursor(3, 0);
    lcd.print("tare...");
    scale.tare();
  }
  
  if (scale.wait_ready_timeout(200)) {
    reading = round(scale.get_units());
    Serial.print("Weight: ");
    Serial.println(reading);
    lcd.setCursor(3, 0);
    lcd.print("Weight: ");
    lcd.print(reading);
    lastReading = reading;
  }
  else {
    Serial.println("HX711 not found.");
  }
}