Hey, I've been having problems with some code that i cannibalized from the example datalogger file. the purpose of the code is to read a voltage and then store the value in a file (datalog.txt) with the time stamp of when it was read. the problem I'm having is that whenever it goes to log the value, i get on the serial monitor "error opening datalog.txt" and I cant figure out why it keeps doing that, it did work but the times were all screwy and giving me 165/165/165 as a date and time. I'm pretty new to Arduinos and the coding so as much info would be much appreciated
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
const int chipSelect = 10;
RTC_DS1307 rtc;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
if (! rtc.isrunning()) {
Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}
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:
return;
}
Serial.println("card initialized.");
}
}
void loop() {
// make a string for assembling the data to log:
String dataString = "";
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 1023.0);
Serial.println(voltage);
String voltages = String(voltage, 3);
DateTime now = rtc.now();
String theyear = String(now.year(), DEC);
String mon = String(now.month(), DEC);
String theday = String(now.day(), DEC);
String thehour = String(now.hour(), DEC);
String themin = String(now.minute(), DEC);
//Put all the time and date strings into one String
dataString = String("voltages, " + theyear + "/" + mon + "/" + theday + ", " + thehour + ":" + themin);
delay(1000);
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
File dataFile = SD.open("datalog.txt", FILE_WRITE);
// if the file is available, write to it:
if (dataFile) {
dataFile.println(dataString);
dataFile.close();
// print to the serial port too:
Serial.println(dataString);
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
DataloggerVoltage.ino (2.17 KB)