#include <HX711.h>
#include <SD.h>
#include <SPI.h>
#include <RTClib.h>
// Pin definitions
#define LOADCELL_DOUT_PIN 2
#define LOADCELL_SCK_PIN 3
#define CS_PIN 10
// Initialize objects
HX711 scale;
RTC_DS3231 rtc; //RTC_DS1307????
File ispFile;
// Variables
float threshold = 0.1; // Minimum load to trigger logging (kg)
bool isLogging = false;
unsigned long lastMeasurement = 0;
const int measureInterval = 12; // For 80Hz (1000ms/80 = 12.5ms)
void setup() {
Serial.begin(9600);
// Initialize scale
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(168.0); // Replace with your calibration value
scale.tare();
Serial.println(F("Scale has been initialized..."));
// Initialize RTC
rtc.begin();
if (!rtc.begin()) { //if the RTC does not begin
Serial.println(F("Couldn't find RTC")); //print to serial monitor
Serial.flush(); //flush old monitor text
while (1) delay(10);
}else{
Serial.println(F("RTC has been initialized..."));} //if RTC is running print to monitor
// Initialize SD card
SD.begin(CS_PIN);
if (!SD.begin(CS_PIN)) {
Serial.println(F("Initialization failed. Things to check:"));
Serial.println(F("1. Is a card inserted?"));
Serial.println(F("2. Is the wiring correct?"));
Serial.println(F("3. Does teh chipselect pin match the shield or module?"));
return;
while (1);
}else{
Serial.println(F("Thrust Logger Initializing"));
Serial.println(F("SD card has been initialized..."));}
}
void loop() {
if (millis() - lastMeasurement >= measureInterval) {
float weight = scale.get_units();
DateTime now = rtc.now();
// Start logging if weight exceeds threshold
if (weight > threshold && !isLogging) {
String filename = String(now.year()) + String(now.month()) + String(now.day()) + "_" +
String(now.hour()) + String(now.minute()) + ".csv";
ispFile = SD.open("myData.txt", FILE_WRITE);
ispFile.println("Time,Weight(kg)");
isLogging = true;
}
// Continue logging while weight is above threshold
if (isLogging) {
if (weight > threshold) {
String dataString = String(now.timestamp()) + "," + String(weight, 3);
ispFile.println(dataString);
ispFile.flush();
} else {
// Stop logging when weight drops below threshold
ispFile.close();
isLogging = false;
}
}
lastMeasurement = millis();
}
}