#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "HX711.h"

// OLED setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// HX711 setup
#define DOUT 1
#define CLK  0
HX711 scale(DOUT, CLK);

// Calibrated scale factor
float scaleFactor = 209.96;

// ---------------- Startup Screen ----------------
void showStartupText() {
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);

  // T
  display.setCursor(5, 24);
  display.print("T");

  // U als inverse blok
  display.fillRect(25, 20, 18, 20, SSD1306_WHITE);  // wit blok
  display.setTextColor(SSD1306_BLACK);              // zwarte tekst
  display.setCursor(27, 24);
  display.print("U");

  // terug naar normaal
  display.setTextColor(SSD1306_WHITE);

  // Delft erachter
  display.setCursor(50, 24);
  display.print("Delft");

  display.display();
  delay(2000);  // 2 seconden tonen
}
// ------------------------------------------------

void setup() {
  Wire.begin();
  Serial.begin(9600);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("OLED failed");
    while (1);
  }

  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);

  scale.set_scale(scaleFactor);

  showStartupText();  // Toon TU Delft tekst bij start

  scale.tare(); // Auto-tare
  Serial.println("Auto-tare complete.");
  Serial.println("HX711 scale ready.");
}

void loop() {
  float weight = -scale.get_units(10);  // Gemiddelde van 10 metingen

  Serial.print("Weight: ");
  Serial.print(weight, 1);
  Serial.println(" g");

  display.clearDisplay();

  // Header
  display.setTextSize(1);
  display.setCursor(15, 5);
  display.print("MEASURING...");

  // Gewicht groot in beeld
  String output = String((int)weight) + " g";
  int textSize = 3;
  int charWidth = 6 * textSize;
  int textWidth = output.length() * charWidth;
  int x = (SCREEN_WIDTH - textWidth) / 2;
  int y = 25;

  display.setTextSize(textSize);
  display.setCursor(x, y);
  display.print(output);

  display.display();
  delay(500);
}
