Trouble storing time

Hello everyone.

I am working on making a data logger for work, and I am using a DS1307 RTC. At the moment, I am using LadyAda’s RTC.lib

I am having trouble figuring out how to store the current unix time to a variable in setup, then in every loop store the current unix time to another variable, subtract the 2 to get total elapsed run time. My plan was to have the loop run full speed to show current LCD stats, but write to an SD card every few minutes, based off an interval.

I hope this is somewhat clear. Please let me know if I am going about this totally wrong, as I am pretty much an arduino noob.

thank you everyone.

/*
  LiquidCrystal Library - Hello World
 
 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the 
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.
 
 This sketch prints "Hello World!" to the LCD
 and shows the time.
 
 The circuit:
 * LCD RS pin to digital pin 12 - 7
 * LCD Enable pin to digital pin 11 - 6
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 
 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe
 
 This example code is in the public domain.
 
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

#include <stdarg.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;


/*
    Basic example reading and writing to the microSD shield
    Based on the SdFat Library by Bill Greiman
    SparkFun Electronics
    
    This example creates a file (or opens it if the file already exists) named 'Test.txt.'
    A string with the value 'Millis: (number of millis)' is appended to the end of the file. 
    After writing to the file, the contents of the entire file are printed to the serial port.
 */
 
//Add the SdFat Libraries
#include <SdFat.h>
#include <SdFatUtil.h> 
#include <ctype.h>

//Create the variables to be used by SdFat Library
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

char name[] = "Test.txt";     //Create an array that contains the name of our file.
char contents[256];           //This will be a data buffer for writing contents to the file.
char in_char=0;
int index=0;                  //Index will keep track of our position within the contents buffer.


int VoltPin = A2;
int AmpPin = A1;
float Volt;
float Amp;
float AmpF;
float VoltAverage;
float AmpAverage;
float VoltIn;
float AmpIn;
float vcons = 26.6819932293214;
float acons = 8.37244144029934;
float watt;
int BDIpin = A3;
float BDI;
float BDIP;
int CENABLE = 9;

int dt6;
int dt7;
int dt8;


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

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

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup() {
  
 /* // connect to RTC
  Wire.begin();
  if (!RTC.begin()) error("RTC failed");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  cout  << now << endl;
  */
  analogReference(DEFAULT);
  // set up the LCD's number of columns and rows: 
  lcd.begin(20, 4);
  // Print a message to the LCD.
  //Serial.begin(9600);

    Wire.begin();
    RTC.begin();

  if (! RTC.isrunning()) {
    lcd.print("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

 // time_t starttime = now(); // = now.unixtime();
 pinMode(CENABLE, OUTPUT);
   //Set Start Time
  DateTime now = RTC.now();
   DateTime dt6 (now.unixtime());
}

void loop() {

  
        int count = 0;
        float totalV = 0;
        float totalA = 0;

        while (count < 512){
                      float VoltIn = analogRead(VoltPin);
                      float AmpIn = analogRead(AmpPin);
                      totalV = VoltIn + totalV;
                      totalA = AmpIn + totalA;
                      //Serial.println(totalV);
                      //lcd.print(count);
                count++;
        }
        VoltAverage = totalV / (float)count;
        AmpAverage = totalA / (float)count;
  Volt = VoltAverage / vcons; //convert 1024 to 38
  AmpF = AmpAverage - 512.0; // 2.5v is 0A, adjusting range
  Amp = AmpF / acons; // convert +- 512 to 50 from center
  watt = Volt * Amp;
  float BDI = analogRead(BDIpin);
  BDIP = BDI / 10.24; // convert to Percent

lcd.clear(); //clear the display

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
 
  lcd.setCursor (0, 0);
  lcd.print(VoltAverage, 0);
  lcd.setCursor (5, 0);
  //lcd.print("Volt");
  //lcd.setCursor(11, 0);
  lcd.print(Volt, 2);
  lcd.print("V");
  
  lcd.setCursor ( 12, 0);
  lcd.print(watt, 0);
  lcd.print("W");
  
  lcd.setCursor(0, 1);
  lcd.print(AmpAverage, 0);
  lcd.setCursor (5, 1);
  //lcd.print("Amp");
  //lcd.setCursor(11, 1);
  lcd.print(Amp, 2);  
  lcd.print("A");
  
  lcd.setCursor(0, 2);
  lcd.print(BDIP, 0);
  //lcd.setCursor (3, 2);
  lcd.print("%");
  lcd.setCursor (5, 2);
  lcd.print("BDI");
  
  lcd.setCursor (9, 2);

  
  lcd.setCursor(0, 3);
  lcd.print("Time");
  lcd.setCursor(5, 3);
  DateTime now = RTC.now();
 // calculate Current Time
   DateTime dt7 (now.unixtime() - dt6);
   // Calculate time since start
   // dt8 = dt7 - dt6;
   
  
 /* lcd.print(" since midnight 1/1/1970 = ");
    lcd.print(now.unixtime());
    lcd.print("s = ");
    lcd.print(now.unixtime() / 86400L);
    lcd.print("d");
  */ 
    
    lcd.print(now.hour(), DEC);
    lcd.print(':');
    lcd.print(now.minute(), DEC);
    lcd.print(':');
    lcd.print(now.second(), DEC);
    lcd.setCursor(10, 2);
    //lcd.print(starttime);
    //lcd.print(' ');
    lcd.print(dt7.unixtime());
  
 
  }
  DateTime now = RTC.now();
  DateTime now = RTC.now();

Now, I really don't think the compiler liked this in setup().

   DateTime dt6 (now.unixtime());

This local variable goes out of scope as soon as setup ends. Pretty much a waste of effort creating it.

The unixtime() method returns a uint32_t, so create a global variable of that type to store the time in.

  DateTime now = RTC.now();
 // calculate Current Time
   DateTime dt7 (now.unixtime() - dt6);

This would be better like so:

uint32_t now = RTC.now().unixtime();

If you called the previous time then,

uint32_t duration = now - then;

And duration is in seconds...

I must be missing something…

/*
  LiquidCrystal Library - Hello World
 
 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the 
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.
 
 This sketch prints "Hello World!" to the LCD
 and shows the time.
 
 The circuit:
 * LCD RS pin to digital pin 12 - 7
 * LCD Enable pin to digital pin 11 - 6
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)
 
 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe
 
 This example code is in the public domain.
 
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

// include the library code:
#include <LiquidCrystal.h>

#include <stdarg.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

// Date and time functions using a DS1307 RTC connected via I2C and Wire lib

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;


/*
    Basic example reading and writing to the microSD shield
    Based on the SdFat Library by Bill Greiman
    SparkFun Electronics
    
    This example creates a file (or opens it if the file already exists) named 'Test.txt.'
    A string with the value 'Millis: (number of millis)' is appended to the end of the file. 
    After writing to the file, the contents of the entire file are printed to the serial port.
 */
 
//Add the SdFat Libraries
#include <SdFat.h>
#include <SdFatUtil.h> 
#include <ctype.h>

//Create the variables to be used by SdFat Library
Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

char name[] = "Test.txt";     //Create an array that contains the name of our file.
char contents[256];           //This will be a data buffer for writing contents to the file.
char in_char=0;
int index=0;                  //Index will keep track of our position within the contents buffer.


int VoltPin = A2;
int AmpPin = A1;
float Volt;
float Amp;
float AmpF;
float VoltAverage;
float AmpAverage;
float VoltIn;
float AmpIn;
float vcons = 26.6819932293214;
float acons = 8.37244144029934;
float watt;
int BDIpin = A3;
float BDI;
float BDIP;
int CENABLE = 9;

uint32_t now;
uint32_t then;
uint32_t duration;


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

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

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup() {
  
 /* // connect to RTC
  Wire.begin();
  if (!RTC.begin()) error("RTC failed");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  cout  << now << endl;
  */
  analogReference(DEFAULT);
  // set up the LCD's number of columns and rows: 
  lcd.begin(20, 4);
  // Print a message to the LCD.
  //Serial.begin(9600);

    Wire.begin();
    RTC.begin();

  if (! RTC.isrunning()) {
    lcd.print("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

 // time_t starttime = now(); // = now.unixtime();
 pinMode(CENABLE, OUTPUT);
   //Set Start Time
  //DateTime now = RTC.now();
   //DateTime then (now.unixtime());
   uint32_t then = RTC.now().unixtime();
}

void loop() {

  
        int count = 0;
        float totalV = 0;
        float totalA = 0;

        while (count < 512){
                      float VoltIn = analogRead(VoltPin);
                      float AmpIn = analogRead(AmpPin);
                      totalV = VoltIn + totalV;
                      totalA = AmpIn + totalA;
                      //Serial.println(totalV);
                      //lcd.print(count);
                count++;
        }
        VoltAverage = totalV / (float)count;
        AmpAverage = totalA / (float)count;
  Volt = VoltAverage / vcons; //convert 1024 to 38
  AmpF = AmpAverage - 512.0; // 2.5v is 0A, adjusting range
  Amp = AmpF / acons; // convert +- 512 to 50 from center
  watt = Volt * Amp;
  float BDI = analogRead(BDIpin);
  BDIP = BDI / 10.24; // convert to Percent

lcd.clear(); //clear the display

  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
 
  lcd.setCursor (0, 0);
  lcd.print(VoltAverage, 0);
  lcd.setCursor (5, 0);
  //lcd.print("Volt");
  //lcd.setCursor(11, 0);
  lcd.print(Volt, 2);
  lcd.print("V");
  
  lcd.setCursor ( 12, 0);
  lcd.print(watt, 0);
  lcd.print("W");
  
  lcd.setCursor(0, 1);
  lcd.print(AmpAverage, 0);
  lcd.setCursor (5, 1);
  //lcd.print("Amp");
  //lcd.setCursor(11, 1);
  lcd.print(Amp, 2);  
  lcd.print("A");
  
  lcd.setCursor(0, 2);
  lcd.print(BDIP, 0);
  //lcd.setCursor (3, 2);
  lcd.print("%");
  lcd.setCursor (5, 2);
  lcd.print("BDI");
  
  lcd.setCursor (9, 2);

  
  lcd.setCursor(0, 3);
  lcd.print("Time");
  lcd.setCursor(5, 3);
  //DateTime now = RTC.now();  // calculate Current Time
   uint32_t now = RTC.now().unixtime();
   // Calculate time since start
   uint32_t duration = now - then;
   
  
 /* lcd.print(" since midnight 1/1/1970 = ");
    lcd.print(now.unixtime());
    lcd.print("s = ");
    lcd.print(now.unixtime() / 86400L);
    lcd.print("d");
  */ 
    
    /*lcd.print(now.hour(), DEC);
    lcd.print(':');
    lcd.print(now.minute(), DEC);
    lcd.print(':');
    lcd.print(now.second(), DEC);
    */
    //lcd.setCursor(10, 2);
    //lcd.print(starttime);
    lcd.print(' ');
    lcd.print(duration);
  
 
  }

This is printing the unix time on my LCD, not duration since program start.

you also can likely guess that lcd.print(now.minute(), DEC); no longer works, and must be commented out to compile.

   uint32_t then = RTC.now().unixtime();

Now you have a global variable named then and a local (soon to go out of scope) variable with the same name.

   uint32_t now = RTC.now().unixtime();
   // Calculate time since start
   uint32_t duration = now - then;

You also have global and local variables named now and duration. The variable then is still 0, so duration measures the time since 1970. Is it safe to assume that that is not the duration of interest?

you also can likely guess that lcd.print(now.minute(), DEC); no longer works, and must be commented out to compile.

Yes, I could. If you want duration in days, hours, minutes, seconds, etc.:
DateTime elapsed(duration);
and print elapsed.minutes(), elapsed.seconds(), etc.

I am going to assume you are referring to me declaring the variables in the beginning.

uint32_t now;
uint32_t then;
uint32_t duration;

However, if I comment this out, it won't compile, due to not having the variables declared.

The goal I am trying to achieve is for the arduino to store its unix time it was turned on, and keep track of how long it has been turned on, so that every 5 minutes it will write variables to a SD card.

I had planned to do an If statement to write to the SD card, something along the lines of "If duration = 300, then store now as then, and write to SD card"

That way, every 300 seconds it will execute that if loop, and write the variables to the SD card, but the program itself doesn't wait for 5 minutes to refresh the LCD screen, that will keep going "live"

I am going to assume you are referring to me declaring the variables in the beginning.

Those are the global ones, yes.

   uint32_t then = RTC.now().unixtime();

This creates a local variable. If you want to store the value in the global variable (and you do), get rid of the type declaration (the uint32_t part).

Well that did the trick!!! Thank you!