sdfatLib with ds1307 time set problem (SOLVED)

I’m new to this so please excuse me if the question was been asked before or is ignorant. I cannot get the correct time with the following

LiquidCrystal lcd(4, 5, 6, 7, 8, 9);
int LDR = 0;                  //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;             //that’s a variable to store LDR values
int light_sensitivity = 600;  //This is the approx value of light surrounding your LDR

#include <SdFat.h>
#include <SdFatUtil.h>  // define FreeRam()

#define SD_CHIP_SELECT  SS  // SD chip select pin
#define USE_DS1307       1  // set nonzero to use DS1307 RTC
#define LOG_INTERVAL  1000  // mills between entries
#define SENSOR_COUNT     1  // number of analog pins to log
#define ECHO_TO_SERIAL   1  // echo data to serial port if nonzero
#define WAIT_TO_START    0  // Wait for serial input in setup()
#define ADC_DELAY       10  // ADC delay for high impedence sensors

// file system object
SdFat sd;

// text file for logging
ofstream logfile;

// Serial print stream
ArduinoOutStream cout(Serial);

// buffer to format data - makes it eaiser to echo to Serial
char buf[80];
#error SENSOR_COUNT too large
#endif  // SENSOR_COUNT
// store error strings in flash to save RAM
#define error(s) sd.errorHalt_P(PSTR(s))
#if USE_DS1307
// use RTClib from Adafruit

// The Arduino IDE has a bug that causes Wire and RTClib to be loaded even
// if USE_DS1307 is false.

#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 RTC;  // define the Real Time Clock object

// call back for file timestamps
void dateTime(uint16_t* date, uint16_t* time) {
    DateTime now =;

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(),;

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
// format date/time
ostream& operator << (ostream& os, DateTime& dt) {
  os << dt.year() << '/' << int(dt.month()) << '/' << int( << ',';
  os << int(dt.hour()) << ':' << setfill('0') << setw(2) << int(dt.minute());
  os << ':' << setw(2) << int(dt.second()) << setfill(' ');
  return os;
#endif  // USE_DS1307
void setup() {
  pinMode(3, OUTPUT);
  while (!Serial){}  // wait for Leonardo
  // pstr stores strings in flash to save RAM
  cout << endl << pstr("FreeRam: ") << FreeRam() << endl;

  cout << pstr("Type any character to start\n");
  while ( <= 0) {}
  delay(400);  // catch Due reset problem
#endif  // WAIT_TO_START

#if USE_DS1307
  // connect to RTC
  if (!RTC.begin()) error("RTC failed");

  // set date time callback function
  DateTime now =;
  cout  << now << endl;
#endif  // USE_DS1307

  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  if (!sd.begin(SD_CHIP_SELECT, SPI_HALF_SPEED)) sd.initErrorHalt();

  // create a new file in root, the current working directory
  char name[] = "LOGGER00.CSV";

  for (uint8_t i = 0; i < 100; i++) {
    name[6] = i/10 + '0';
    name[7] = i%10 + '0';
    if (sd.exists(name)) continue;;
  if (!logfile.is_open()) error("");

  cout << pstr("Logging to: ") << name << endl;
  cout << pstr("Type any character to stop\n\n");
  // format header in buffer
  obufstream bout(buf, sizeof(buf));

  bout << pstr("millis");

#if USE_DS1307
  bout << pstr(",date,time");
#endif  // USE_DS1307

  for (uint8_t i = 0; i < SENSOR_COUNT; i++) {
    bout << pstr(",sens") << int(i);
  logfile << buf << endl;

  cout << buf << endl;
#endif  // ECHO_TO_SERIAL
void loop() {
  lcd.print(analogRead (A0));
  LDRValue = analogRead(LDR);          //reads the ldr’s value through LDR which we have set to Analog input 0 “A0?
    Serial.println(LDRValue);                  //prints the LDR values to serial monitor
    if (LDRValue > light_sensitivity) 
  digitalWrite(3, HIGH);
  digitalWrite(3, LOW);
    if (LDRValue < light_sensitivity) 
  digitalWrite(3, LOW);

  uint32_t m;

  // wait for time to be a multiple of interval
  do {
    m = millis();
  } while (m % LOG_INTERVAL);

  // use buffer stream to format line
  obufstream bout(buf, sizeof(buf));

  // start with time in millis
  bout << m;

#if USE_DS1307
  DateTime now =;
  bout << ',' << now;
#endif  // USE_DS1307

  // read analog pins and format data
  for (uint8_t ia = 0; ia < SENSOR_COUNT; ia++) {
#endif  // ADC_DELAY
    bout << ',' << analogRead(ia);
  bout << endl;

  // log data and flush to SD
  logfile << buf << flush;

  // check for error
  if (!logfile) error("write data failed");

  cout << buf;
#endif  // ECHO_TO_SERIAL

  // don't log two points in the same millis
  if (m == millis()) delay(1);
  if (!Serial.available()) return;
  cout << pstr("Done!");
  while (1);


The second line of your code is doubtful.

int LDR=0

means the variable LDR=0, in exactly the same manner as LDRValue=0, and 0 does not mean A0. If you want to call pin A0 by a number, call it 14 if a Uno or 44 for Mega, but I think you are better off sticking with calling it A0, which works for both.

define LDR A0 might work.....

I wouldn't be too sure about line 1 either. I can't follow any of the code and have no idea how the SD is selected, but using pin 4 for the LCD is probably, or soon will be, a recipe for disaster, as I believe it is inviting a clash with the SD.

It doesn't matter whether you refer to the analog pin as 0, A0 or 14 (on a UNO). If you specify a pin number (e.g. 14) to analogRead(), the library maps the pin number to the ADC channel number (0). I believe that the A0 pin on a Mega is digital pin 54 - that's what Grumpy_Mike and the library's code says and who am I to argue? :)


Oops, yes, add 40 to pin number, not replace the A with 4. Not that I think that is relevant to this problem..... And it's only recently that I have changed all my analogue calls to Ax.

I have noticed an occasional bug with the lid read and thank you for the input I will reevaluate it but I not sure that would affect the time. Is the time set via the sketch each time it's uploaded or is it set with a separate sketch prior? Sorry total newbie thanks I guess i don't exactly follow how this sketch sets the time. I have run another sketch were it was pretty straight forward.

Time Problem solved. I pulled the RTC and its battery reset time and now it works! weird

I see what your saying about the RTC on A4 and the LCD on pin 4, should i move the lcd pin?

Yes, but not because of the clock. The DS1307 uses the I2C bus, being A4,A5 on the Uno, i.e. pins 18,19. Pin 4 is commonly used by the SD card. You code suggests the LCD is a bare display and therefore you just jump it to a vacant pin. If it is a shield, you should be able to solder a wire from D4 to anything vacant and convenient and clip the pin. I have proto shields between the main board and the LCD and did the jumping and clipping there. Not a good idea.

the lcd is bare one and the sd is a shield. The sd uses pin 10 for cs not 4 is this still an issue? I could move lcd pin 4 to 3.

Now im wondering if I should relabel this thread or start a new one. lol

the lcd is bare one and the sd is a shield. The sd uses pin 10 for cs not 4 is this still an issue?

On reflection, if it’s working OK, probably not an issue. I think I now realise what is going on. Your SD is a shield but all my SDs are either built in to the main board or incorporated into the Ethernet shield, and I use the standard SD library. In those cases SS is on pin 4 but, on the Uno, pin 10 must be kept as output. I have just learned that this is apparently determined in the SD library. I have never used SDFat.h.

the problem is strange it works good and every now and then the sd with record a ###### date (but the time records fine) and the lcd will give me gibberish then it will resume working, some times on its own sometime needs a reset, but the rest of the program continues. I still haven't had it running long enough it pin down the problem. Plus I'm really new to all of this, and i have been figuring every thing out as i go. Thanks for all the help

easterly81: the problem is strange it works good and every now and then the sd with record a ###### date (but the time records fine) and the lcd will give me gibberish then it will resume working, some times on its own sometime needs a reset, but the rest of the program continues.

As a longshot, if you are using the USB cable for power, it might not be up to the job, thereby causing erratic behaviour. There seems to be all sorts of superfluous nonsense in the code but that apparently doesn't stop it from working, so it's not so likely to be the problem.

I'm using a 9v 700 ma charger. I never thought of that is 700 ma enough?