#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;
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);
Serial.println(F("Thrust Logger Initializing"));
Serial.println(F("Scale has been initialized..."));
Serial.println(F("RTC has been initialized..."));
Serial.println(F("SD card has been initialized..."));
// Initialize scale
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(168.0); // Replace with your calibration value
scale.tare();
// Initialize RTC
rtc.begin();
// Initialize SD card
SD.begin(CS_PIN);
}
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();
}
}