I am super new and looking for help.
I have an uno with a micro SD module and a moisture sensor. I found a small 2G micro SD card, and everything initializes fine, I used the built-in cardinfo to verify the SD.
But when I try to open/write to the file it doesn't work. I've used the built-in datalogger as well and it still kicks back errors.
I'm having trouble figuring out what else to look for. I've tried fixing my code, using different methods that I've found on youtube, but nothing is working so far. Any ideas would be awesome. Thanks guys.
#include <SPI.h>
#include <SD.h>
File dataFile;//Create the file object
String fileName = "test.csv";//Name the file
const int chipSelect = 10;
//first calibrate dry sensor value and pure water. We might want to consider calibrating under extremely dry conditions if we want more accuracy in drier values.
const int dry = 580; // value for dry sensor
const int wet = 300; // value for wet sensor
void setup()
{
Serial.begin(9600);//this is the baud rate, don't change
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
if (SD.exists(fileName)) //check for existing or duplicate file names
{
Serial.println("File exists");
}
else
Serial.println("File does not exist");
dataFile = SD.open(fileName,FILE_WRITE);//Create the file
dataFile.close();
// if the file was created successfully, open and write to it:
if (dataFile) {
Serial.println("File opened ok");
// print the headings for our data
dataFile.println("Time,Percent Moisture,Reading");
Serial.println("Time,Percent Moisture,Reading");
dataFile.close();
}
}
void loop()
{
int sensorVal = analogRead(A1);
int percentMoisture = map(sensorVal, wet, dry, 100, 0);
//Write data to file
if (dataFile) {
dataFile.print(percentMoisture);
dataFile.print("%");
dataFile.print(",");
dataFile.println(analogRead(A1));
Serial.print(percentMoisture);
Serial.print("%");
Serial.print(",");
Serial.println(analogRead(A1));//A0 is where we have the AOUT plugged in, change this if you move the wire to a new location
dataFile.close(); //Close the file
}
else
Serial.println("OOPS!! SD card writing failed");
delay(5000);//this is the delay between readings in milliseconds
}
Serial monitor output: