const byte DOUT_PIN = A1;
const byte SCK_PIN = A0;
const byte TARA_PIN = 5;
long reading = 0;
float calibration_factor = 840.0; // Fator de calibração (ajuste conforme necessário)
float tare = 0;

void setup() {
  Serial.begin(9600);
  pinMode(DOUT_PIN, INPUT);
  pinMode(SCK_PIN, OUTPUT);
  digitalWrite(SCK_PIN, HIGH);
  pinMode(TARA_PIN, INPUT_PULLUP);
  reading = read_raw_data();
  tare = (reading / calibration_factor);
  Serial.println("Tara definida.");
}

void power_up() {
  digitalWrite(SCK_PIN, LOW);
  delayMicroseconds(1);
}

void power_down() {
  digitalWrite(SCK_PIN, HIGH);
  delayMicroseconds(1);
}

long read_raw_data() {
  long count = 0;
  power_down();
  power_up();
  delayMicroseconds(1);
  for(int i = 0; i < 24; i++) {
    digitalWrite(SCK_PIN, HIGH);
    delayMicroseconds(1);
    count = count << 1;
    if(digitalRead(DOUT_PIN) == HIGH) {
      count++;
    }
    digitalWrite(SCK_PIN, LOW);
    delayMicroseconds(1);
  }
  count = count ^ 0x800000;
  return count;
}

void loop() {
  reading = read_raw_data();
  float weight = (reading / calibration_factor) - tare;
  
  if (digitalRead(TARA_PIN) == LOW) {
    tare = (reading / calibration_factor);
    Serial.println("Tara definida.");
  }

  Serial.print("Weight: ");
  Serial.print(weight);
  Serial.println(" kg");
  delay(1000);
}