#include <Wire.h>
#include "HX711.h"

const int NUM_LOADCELLS = 4;

// Pins for load cells (DOUT, SCK)
const int LOADCELL_DOUT_PINS[NUM_LOADCELLS] = {2, 4, 12, 10};
const int LOADCELL_SCK_PINS[NUM_LOADCELLS] = {3, 5, 11, 9};
float bweight = 12500.0;  // Bogie weight in kg
HX711 scales[NUM_LOADCELLS];

// Calibration factors (replace these with your actual calibration values)
const float scale_factors[NUM_LOADCELLS] = {
    100000.0 / 2100.0,  // Scale factor for load cell 1 (kg per ADC point)
    100000.0 / 2100.0,  // Scale factor for load cell 2 (kg per ADC point)
    100000.0 / 2100.0,  // Scale factor for load cell 3 (kg per ADC point)
    100000.0 / 2100.0   // Scale factor for load cell 4 (kg per ADC point)
};

const float offsets[NUM_LOADCELLS] = {0.0, 0.0, 0.0, 0.0};  // Offsets for each load cell

const int PHOTOCELL_PIN_1 = A6;   // Analog input for photoresistor 1
const int PHOTOCELL_PIN_2 = A5;   // Analog input for photoresistor 2
const int PHOTOCELL_THRESHOLD = 800;  // Threshold value for photoresistor activation

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < NUM_LOADCELLS; i++) {
    scales[i].begin(LOADCELL_DOUT_PINS[i], LOADCELL_SCK_PINS[i]);
    Serial.print("Initiating tare for load cell ");
    Serial.println(i + 1);
    scales[i].tare();
  }
}
void loop() {
  // Read photoresistor values
  int photoValue1 = analogRead(PHOTOCELL_PIN_1);
  int photoValue2 = analogRead(PHOTOCELL_PIN_2);
  // Check if both photoresistors have values above the threshold
  //if (photoValue1 > PHOTOCELL_THRESHOLD && photoValue2 > PHOTOCELL_THRESHOLD) {
    // Read raw ADC readings from load cells
    long rawValues[NUM_LOADCELLS];
    for (int i = 0; i < NUM_LOADCELLS; i++) {
      rawValues[i] = scales[i].read();
    }  
    // Convert raw ADC readings to weights in kilograms
    float weights[NUM_LOADCELLS];
    for (int i = 0; i < NUM_LOADCELLS; i++) {
      weights[i] = (rawValues[i] < offsets[i]) ? 0 : (rawValues[i] - offsets[i]) * scale_factors[i];
    }
    // Calculate the average weight
    float totalWeight = 0;
    for (int i = 0; i < NUM_LOADCELLS; i++) {
      totalWeight += weights[i];
    }
    float averageWeight = totalWeight / NUM_LOADCELLS;
    
    // Subtract bogie weight
    averageWeight -= bweight;
    
    // Display the average weight if it's positive
    if (averageWeight > 0) {
      Serial.print("Coal  Weight (kg): ");
      Serial.println(averageWeight, 2);
    }
  //}
  delay(1000);  // Delay for 1 second between readings
}