#include <SPI.h>
#include <SD.h>
const int lm35Pin = A0; // LM35 output connected to analog pin A0
const int SDCard = 4; // CS pin
//Array variables
const int totalReads = 10; // Number of readings to take for averaging
float readings[totalReads]; // Array to store the readings
int readIndex = 0; // Index of the current reading
float total = 0; // Total of the readings
float ftime = 0;
const float BETA = 3950;
void setup() {
Serial.begin(9600); // Start the serial communication
Serial.println("Reading for card...");
if (!SD.begin(SDCard)) {
Serial.println("Card failed, or not present");
}
else{
Serial.println("Card Found!");
File dataFile = SD.open("data.csv", FILE_WRITE);
if (dataFile) {
dataFile.println("Time,Temperature (°F)");
dataFile.close();
}
}
}
void loop() {
// Read the analog value from sensor
//adc analoge digital converter into voltage (5.0 / 1023.0) turned to Celsius (voltage * 100.0) finally turned to Fereignheigt (C * 9.0 / 5.0)
int adcValue = analogRead(lm35Pin);
float celsius = 1 / (log(1 / (1023.0 / adcValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
float temperatureF = (celsius * (1.8)) + 32;
// Add the new reading to the total
total = total + temperatureF;
// Store the reading in the array
readings[readIndex] = temperatureF;
// next position of array
readIndex++;
//fake "time" to figure out how many repititions it had gone through the night.
Serial.println(temperatureF) ;
// If we're at the end of the array, wrap around to the beginning
if (readIndex >= totalReads) {
readIndex = 0;
float average = total / totalReads;
Serial.print("Average Temperature: ");
Serial.print(average);
Serial.println("°F");
writeToFile("data.csv", ftime, average);
total = 0;
ftime++;
}
delay(1000); // Wait for a second before reading again
}
void writeToFile(const char* filename, float time, float data) {
// Open a file for writing
File dataFile = SD.open(filename, FILE_WRITE);
// If the file is available, write to it
if (dataFile) {
dataFile.print(time);
dataFile.print(",");
dataFile.println(data);
dataFile.close();
Serial.println("Data written to file.");
} else {
// If the file didn't open, print an error
Serial.println("Error opening file for writing.");
}
}