#include <SD.h>
#define CS_PIN 10
File root;
const float BETA = 3950; // should match the Beta Coefficient of the thermistor
void setup() {
Serial.begin(115200);
Serial.print("Initializing SD card... ");
if (!SD.begin(CS_PIN)) {
Serial.println("Card initialization failed!");
while (true);
}
Serial.println("initialization done.");
//Serial.println("Files in the card:");
root = SD.open("/");
//printDirectory(root, 0);
Serial.println("");
//File writeFile = SD.open("temp.txt", FILE_WRITE);
//writeFile.write("Writing temperature to SDcard.\n\n");
//writeFile.close();
/*
// Example of reading file from the card:
File textFile = SD.open("temp.txt");
if (textFile) {
Serial.print("temp.txt: ");
while (textFile.available()) {
Serial.write(textFile.read());
}
textFile.close();
} else {
Serial.println("error opening temperature.txt!");
}
*/
}
void loop() {
Serial.println();
Serial.print("Measuring the temperature five times:\n");
File writeFile = SD.open("temp.txt", FILE_WRITE);
for (int i=1; i<6; i++) {
Serial.print("Temperature ");
Serial.print(i);
Serial.print(" is ");
int analogValue = analogRead(A0);
float celsius = random(-10,10)*0.1 + 1 / (log(1 / (1023. / analogValue - 1)) / BETA + 1.0 / 298.15) - 273.15;
//Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" Celcius. Saved to the SDCard.");
writeFile.write(celsius);
delay(1000);
}
writeFile.close();
Serial.println();
Serial.println("Now reading the last 5 temperature values from the SDcard.");
File textFile = SD.open("temp.txt");
if (textFile) {
Serial.print("Reading the SDcard: ");
Serial.println();
while (textFile.available()) {
Serial.write(textFile.read());
}
textFile.close();
} else {
Serial.println("error opening temp.txt!");
}
Serial.println();
delay(2000);
}
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
Serial.println("/");
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}