/*
SD_Card_Test
*/
#include <SPI.h>
#include "SdFat.h"
SdFat SD;
const int potPin = A0; // Analog input pin for potentiometer
int adcValue = 0; // Store raw ADC value
float voltage = 0.0;
unsigned long previousMillis = 0;
unsigned long interval = 5000;
const uint8_t chipSelect = 10;
const float GAMMA = 0.7;
const float RL10 = 50;
int ldrValue = 0;
float ldrVoltage = 0;
float resistance = 0;
float lux = 0;
File TimeFile;
File VoltFile;
File ADCFile;
File LuxFile;
void setup() {
Serial.begin(9600);
SD.begin(chipSelect); // Initialize the SD card module at the Chip Select (CS) pin
SD.ls(LS_R | LS_SIZE);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
potValues();
TimeFile = SD.open("TIME.txt", FILE_WRITE);
if (TimeFile) {
TimeFile.println(currentMillis);
TimeFile.close();
}
VoltFile = SD.open("VOLT.txt", FILE_WRITE);
if (VoltFile) {
VoltFile.println(voltage);
VoltFile.close();
}
ADCFile = SD.open("ADC.txt", FILE_WRITE);
if (ADCFile) {
ADCFile.println(adcValue);
ADCFile.close();
}
LuxFile = SD.open("LUX.txt", FILE_WRITE);
if (LuxFile) {
LuxFile.println(lux);
LuxFile.close();
}
// After writing values, read back and print:
printFile("TIME.txt");
printFile("VOLT.txt");
printFile("ADC.txt");
printFile("LUX.txt");
}
}
// === Functions ===
void potValues() {
adcValue = analogRead(potPin);
voltage = adcValue * (5.0 / 1024);
// These constants should match the photoresistor's "gamma" and "rl10" attributes
const float GAMMA = 0.7;
const float RL10 = 50;
// Convert the analog value into lux value:
ldrValue = analogRead(A1);
ldrVoltage = ldrValue / 1024. * 5;
resistance = 2000 * ldrVoltage / (1 - ldrVoltage / 5);
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
}
// === Function to dump file contents ===
void printFile(const char *filename) {
File file = SD.open(filename);
if (file) {
Serial.print("Contents of ");
Serial.println(filename);
while (file.available()) {
Serial.write(file.read()); // print character by character
}
file.close();
Serial.println(); // add a blank line
} else {
Serial.print("Error opening ");
Serial.println(filename);
}
}