#include <LiquidCrystal_I2C.h>
#include <SD.h>
#define LDR_PIN 2
#define CS_PIN 10
// LDR Characteristics
const float GAMMA = 0.7;
const float RL10 = 50;
String filename = "arduino.txt";
char MyCharArray[] = "Start";
byte myByteArray[] = {'1', '2', '3', '4', '5'};
LiquidCrystal_I2C lcd(0x27, 20, 4);
File root;
File myFile;
void setup() {
pinMode(LDR_PIN, INPUT);
lcd.init();
lcd.backlight();
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("");
//Reading file from the card:
File textFile = SD.open("wokwi.txt");
if (textFile) {
Serial.print("wokwi.txt: ");
while (textFile.available()) {
Serial.write(textFile.read());
}
textFile.close();
} else {
Serial.println("error opening wokwi.txt!");
}
//Creating new file for writing:
myFile = SD.open(filename, FILE_WRITE);
if (myFile) {
myFile.println("test of writing more text");
Serial.println("file writing test complete");
for (int i = 0; i < 5; i++) {
myFile.write(myByteArray[i]);
if (i < 4)
myFile.write(",");
}
myFile.write("\n");
for (int k = 1; k < 5; k++) {
int analogValue = analogRead(A0);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
myFile.println(analogValue);
myFile.println(voltage);
myFile.println(lux);
Serial.print("Voltage ");
Serial.println(voltage);
Serial.print("Analog Value ");
Serial.println(analogValue);
Serial.print("Lux ");
Serial.println(lux);
lcd.setCursor(2, 0);
lcd.print("Room: ");
if (lux > 50) {
lcd.print("Light!");
} else {
lcd.print("Dark ");
}
lcd.setCursor(0, 1);
lcd.print("Lux: ");
lcd.print(lux);
lcd.print(" ");
delay(1000);
}
myFile.close();
} else {
Serial.println("error opening file to write!");
}
// Read the data on the new file
myFile = SD.open(filename);
if (myFile) {
Serial.print(filename);
Serial.println(": opened");
while (myFile.available()) {
Serial.write(myFile.read());
}
myFile.close();
} else {
Serial.println("error opening file for reading!");
}
Serial.println("file reading complete");
}
void loop() {
}
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();
}
}