.96 OLED with arduino uno programming problem

Hi,
I am using arduino Uno for displaying load cell value in .96 OLED display. Communication is through I2C. I am using HX711 as ADC.

The code does show current sensor value(current load cell value) and saves the data in a logger file in SD card. I want to get max sensor value from beginning to current time, save it in logger file and display it in .96 OLED display. How can i do that?

Any help is really appreciated. I have attached my current schematic and current code.

//check font here: https://github.com/olikraus/u8g2/wiki/fntlist8x8





#include <Arduino.h>

#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
#include <SD.h>
//#include <Wire.h>
#include "RTClib.h"
#include "HX711.h"  //You must have this library in your arduino library folder
/****************************************************************************************************************/
/****************************************************************************************************************/
/****************************************************************************************************************/
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
//#define SCREEN_WIDTH 128 // OLED display width, in pixels
//#define SCREEN_HEIGHT 64 // OLED display height, in pixels
//#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)

/****************************************************************************************************************/
/****************************************************************************************************************/
/*************************************************VARIABLES******************************************************/
U8X8_SSD1306_64X32_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

/*************************************************VARIABLES******************************************************/
#define DURATION 2                  //Number of hours, here 2 hours you want this program to run once the button is pressed
#define LOG_INTERVAL 200            //Milliseconds between entries (reduce to take more/faster data)
#define SYNC_INTERVAL 50          // millis between calls to flush() - to write data to the card
uint32_t syncTime = 0;              // time of last sync()
uint32_t start_time;

#define ECHO_TO_SERIAL 1            //Echo data to serial port
//Easy method to turn serial printing on and off. Set to 0 if you don't want to print to the Serial Monitor
RTC_DS1307 RTC;                     //define the Real Time Clock object
const int chipSelect = 10;          //for the data logging shield, we use digital pin 10 for the SD cs line
char timestamp[30];
const int pushbutton = 8;
const int done_light = 9;
int m = 0;
/***All the variables for voltage reading function***/
//the logging file
File bhoomiFile;
//Hx711 pins:
#define DOUT  3
#define CLK  2
HX711 scale;
int average = 0;
//Change this calibration factor as pe
//float calibration_factor = 122541;// for 20g load cell
float calibration_factor = 7311.899902; //7383.399902;//7370.040039; //7370.379882; // for 100g load cell
/****************************************************************************************************************/
/****************************************************SETUP*******************************************************/


void setup()
{
  scale.begin(DOUT, CLK);
  u8x8.clear();
  Serial.println("Press T to tare");
  scale.set_scale(calibration_factor);  //Calibration Factor obtained from first sketch
  scale.tare();             //Reset the scale to 0
#if ECHO_TO_SERIAL
  Serial.println("Press button to start");                                //Prompt user to press button
#endif
  pinMode(pushbutton, INPUT);                 //Set pushbutton as Input
  pinMode(done_light, OUTPUT);                //Set the LED as an output
  digitalWrite(done_light, LOW);              //Make sure the LED is off when we start the program
  Serial.begin(9600);                         //Initialize the serial communication

  u8x8.begin();

  u8x8.setFont(u8x8_font_courR18_2x3_r );
  //u8x8.setFont(u8x8_font_amstrad_cpc_extended_r);

  delay(100);

  while (digitalRead(pushbutton)) {};                                       //Wait for pushbutton input
#if ECHO_TO_SERIAL
  Serial.println("(BUTTON PRESSED!)");                                    //Once pressed, display a message saying so
#endif

  //delay(1000);                                                              //Display the message for a second
  SD_INIT();
  createFile();

  //connect to RTC
  Wire.begin();                                                     //Wire.begin: Initiate the Wire library and join the I2C bus as a master or slave.
  if (!RTC.begin())                                                 //RTC.begin initializes the internal RTC. It needs to be called before any other RTC library methods
  { //Assume that it returns 1 on success and 0 on failure
    bhoomiFile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  bhoomiFile.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g)");        //If RTC initializes successfully...set this as a header in the file
#if ECHO_TO_SERIAL
  Serial.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g)");
#endif //ECHO_TO_SERIAL
  start_time = millis();              //The very next step after this will be the data recording
  //Therefore, note down the time at this moment as the start time
}
/****************************************************************************************************************/

/*************************************************LOOP***********************************************************/
void loop()
{
  //Below: As long as current time - start time < required duration, keep recording the data
  for (start_time; (millis() - start_time) < (DURATION * 60 * 60 * 1000L); )
    //To have record time in HOURS: (DURATION * 60 * 60 * 1000L)

  {
    doTheThing();
  }

  u8x8.clear();
  while (1)
  {
#if ECHO_TO_SERIAL
    Serial.println("ALL DONE");           //Once the set amount of time has passed, display message saying so
#endif //ECHO_TO_SERIAL
    digitalWrite(done_light, HIGH);
    u8x8.print(" Done storing   ");
    u8x8.setFont(u8x8_font_8x13B_1x2_n);
    // u8x8.drawString(1, 1, " Done storing  ");
    u8x8.drawString(1, 2, " 2 hrs ");
  }
}
/****************************************************************************************************************/

/************************************************FUNCTIONS*******************************************************/

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while (1);
}

void SD_INIT()
{
  Serial.print("Initializing SD card...");
  pinMode(chipSelect, OUTPUT);

  //Check if the card is present and can be initialized:
  if (!SD.begin(chipSelect))                                      //SD.begin initializes the SD library and card; Returns 1 on success, 0 on failure
  {
    //lcd.println("SD Card failed");
    u8x8.println(" SD failed      ");
    //    delay(30);
    //    error("Card failed, or not present");                         //Error function displays the error message if SD.begin fails and returns 0
    return;
  }
  Serial.println("card initialized.");                            //If SD.begin is successful
}

void createFile()
{
  //u8x8.setFont(u8x8_font_profont29_2x3_n);
  // create a new file
  char filename[] = "00.CSV";
  for (uint8_t i = 0; i < 200; i++)                               //Make a new file every time the Arduino starts up
  { //Goes from 00 to 99
    filename[0] = i / 10 + '0';
    filename[1] = i % 10 + '0';
    if (!SD.exists(filename))                                     //SD.exists() tests whether a file or directory exists on the SD card
    { //It returns true if the file or directory exists, false if not
      //only open a new file if it doesn't exist
      bhoomiFile = SD.open(filename, FILE_WRITE);                 /*SD.open() opens a file on the SD card. If the file is opened for writing,
                                                                 it will be created if it doesn't already exist (but the directory containing it must already exist).
                                                                  It returns a File object referring to the opened file; if the file couldn't be opened,
                                                                  this object will evaluate to false in a boolean context*/
      //FILE_WRITE enables read and write access to the file
      break;  // leave the loop!
    }
  }

  if (!bhoomiFile)                                                //If file couldn't be opened/created
  {
    error("couldn't create file");
  }
  Serial.print("  Logging to: ");                                   //Otherwise, display the name of the file generated
  Serial.print(filename);
  //u8x8.clear();
  u8x8.setFont(u8x8_font_courR18_2x3_r);
  //u8x8.setCursor(64, 120);
  u8x8.setCursor(-3, 19);
  u8x8.print(filename);

  //u8x8.clear();
  // u8x8.refreshDisplay();
  delay(20);
}

void doTheThing()
{
  DateTime now;

  //delay for the amount of time we want between readings
  delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

  //fetch the time
  now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  Serial.println(timestamp);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print(" , ");

  //now = RTC.now();
  bhoomiFile.print("  ");                  //This space is important. If you remove this, the seconds will not be recorded in the log file
  bhoomiFile.print(now.month(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.day(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.year(), DEC);
  bhoomiFile.print(" ");
  bhoomiFile.print(now.hour(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.minute(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.second(), DEC);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print("");
#if ECHO_TO_SERIAL
  //      Serial.print(now.month(), DEC);
  //      Serial.print("/");
  //      Serial.print(now.day(), DEC);
  //      Serial.print("/");
  //      Serial.print(now.year(), DEC);
  //      Serial.print(" ");
  //      Serial.print(now.hour(), DEC);
  //      Serial.print(":");
  //      Serial.print(now.minute(), DEC);
  //      Serial.print(":");
  //      Serial.print(now.second(), DEC);
  //      Serial.print("");
  //       Serial.print(millis(),DEC);
  //        Serial.print("");
#endif //ECHO_TO_SERIAL
  //Log the voltage reading
  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(scale.get_units() * 1, 4);        //read upto 4 decimal

//Log max voltage reading

m=max(scale.get_units(),1);
  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(m * 1, 4);        //read upto 4 decimal
  
#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(scale.get_units() * 1, 4);       //read upto 4 decimal
  Serial.print("g ");                           //Unit in gram
#endif //ECHO_TO_SERIAL

  bhoomiFile.println();
  //    #if ECHO_TO_SERIAL
  //      Serial.println();
  //    #endif // ECHO_TO_SERIAL
  u8x8.setFont(u8x8_font_courR18_2x3_r);
  u8x8.setCursor(90, 32);
  //u8x8.print("g,       ");                 //Unit in gram
  u8x8.print("       g ");                 //Unit in gram
  u8x8.print(scale.get_units() * 1, 3);  //read upto 4 decimal point

  // u8x8.setFont(u8x8_font_artossans8_n);
  // u8x8.setCursor(30,0);
  //  u8x8.print("Max ");                 //Unit in gram


  if (Serial.available())
  {
    char temp = Serial.read();
    if (temp == 't' || temp == 'T')
      scale.tare();  //Reset the scale to zero
    if (temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if (temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
  delay(50);

  //When you use file.write(), it doesn't write to the card until you flush() or close().
  //Whenever you open a file, be sure to close it to save your data.
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();
  bhoomiFile.flush();               //flush() ensures that any bytes written to the file are physically saved to the SD card
}

/****************************************************************************************************************/

Measure your input and save it to a variable . Next measurement cycle , compare measured value with that in your variable , if it’s bigger replace it , if not do nothing

Change this...

to...
m=max(scale.get_units(),m);

and m will contain the maximum value read.

1 Like

Hi,
Here I kept max value inside the variable maxi. But I do not see proper maximum value. Where am I messing up? I have attached current code and a sample file where last column saves maximum value.

Please help.
26.pdf (89.3 KB)

//check font here: https://github.com/olikraus/u8g2/wiki/fntlist8x8





#include <Arduino.h>

#include <U8x8lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
#include <SD.h>
//#include <Wire.h>
#include "RTClib.h"
#include "HX711.h"  //You must have this library in your arduino library folder
/****************************************************************************************************************/
/****************************************************************************************************************/
/****************************************************************************************************************/
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
//#define SCREEN_WIDTH 128 // OLED display width, in pixels
//#define SCREEN_HEIGHT 64 // OLED display height, in pixels
//#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)

/****************************************************************************************************************/
/****************************************************************************************************************/
/*************************************************VARIABLES******************************************************/
U8X8_SSD1306_64X32_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

/*************************************************VARIABLES******************************************************/
#define DURATION 0.0166667                  //Number of hours, here 2 hours you want this program to run once the button is pressed
#define LOG_INTERVAL 200            //Milliseconds between entries (reduce to take more/faster data)
#define SYNC_INTERVAL 50          // millis between calls to flush() - to write data to the card
uint32_t syncTime = 0;              // time of last sync()
uint32_t start_time;

#define ECHO_TO_SERIAL 1            //Echo data to serial port
//Easy method to turn serial printing on and off. Set to 0 if you don't want to print to the Serial Monitor
RTC_DS1307 RTC;                     //define the Real Time Clock object
const int chipSelect = 10;          //for the data logging shield, we use digital pin 10 for the SD cs line
char timestamp[30];
const int pushbutton = 8;
const int done_light = 9;
float m = 0;
float maxi = 0;
/***All the variables for voltage reading function***/
//the logging file
File bhoomiFile;
//Hx711 pins:
#define DOUT  3
#define CLK  2
HX711 scale;
int average = 0;
//int m = 0;
//Change this calibration factor as pe
//float calibration_factor = 122541;// for 20g load cell
float calibration_factor = 7311.899902; //7383.399902;//7370.040039; //7370.379882; // for 100g load cell




/****************************************************************************************************************/
/****************************************************SETUP*******************************************************/


void setup()
{
  scale.begin(DOUT, CLK);
  u8x8.clear();
  Serial.println("Press T to tare");
  scale.set_scale(calibration_factor);  //Calibration Factor obtained from first sketch
  scale.tare();             //Reset the scale to 0
#if ECHO_TO_SERIAL
  Serial.println("Press button to start");                                //Prompt user to press button
#endif
  pinMode(pushbutton, INPUT);                 //Set pushbutton as Input
  pinMode(done_light, OUTPUT);                //Set the LED as an output
  digitalWrite(done_light, LOW);              //Make sure the LED is off when we start the program
  Serial.begin(9600);                         //Initialize the serial communication

  u8x8.begin();
  u8x8.setFont(u8x8_font_courR18_2x3_r );
  //u8x8.setFont(u8x8_font_amstrad_cpc_extended_r);

  delay(100);

  while (digitalRead(pushbutton)) {};                                       //Wait for pushbutton input
#if ECHO_TO_SERIAL
  Serial.println("(BUTTON PRESSED!)");                                    //Once pressed, display a message saying so
#endif

  //delay(1000);                                                              //Display the message for a second
  SD_INIT();
  createFile();

  //connect to RTC
  Wire.begin();                                                     //Wire.begin: Initiate the Wire library and join the I2C bus as a master or slave.
  if (!RTC.begin())                                                 //RTC.begin initializes the internal RTC. It needs to be called before any other RTC library methods
  { //Assume that it returns 1 on success and 0 on failure
    bhoomiFile.println("RTC failed");
#if ECHO_TO_SERIAL
    Serial.println("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  bhoomiFile.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g)");        //If RTC initializes successfully...set this as a header in the file
#if ECHO_TO_SERIAL
  Serial.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g)");
#endif //ECHO_TO_SERIAL
  start_time = millis();              //The very next step after this will be the data recording
  //Therefore, note down the time at this moment as the start time
}



/****************************************************************************************************************/

/*************************************************LOOP***********************************************************/
void loop()
{
  //Below: As long as current time - start time < required duration, keep recording the data
  for (start_time; (millis() - start_time) < (DURATION * 60 * 60 * 1000L); )
    //To have record time in HOURS: (DURATION * 60 * 60 * 1000L)

    // int maxi = max(scale.get_units(), maxi);

    //  //Log max voltage reading




    //m=max(scale.get_units(),m);

  {
    doTheThing();
  }

  u8x8.clear();
  while (1)
  {
#if ECHO_TO_SERIAL
    Serial.println("ALL DONE");           //Once the set amount of time has passed, display message saying so
#endif //ECHO_TO_SERIAL
    digitalWrite(done_light, HIGH);
    u8x8.print(" Done storing   ");
    u8x8.setFont(u8x8_font_8x13B_1x2_n);
    // u8x8.drawString(1, 1, " Done storing  ");
    u8x8.drawString(1, 2, " 2 hrs ");
  }
}
/****************************************************************************************************************/

/************************************************FUNCTIONS*******************************************************/

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while (1);
}

void SD_INIT()
{
  Serial.print("Initializing SD card...");
  pinMode(chipSelect, OUTPUT);

  //Check if the card is present and can be initialized:
  if (!SD.begin(chipSelect))                                      //SD.begin initializes the SD library and card; Returns 1 on success, 0 on failure
  {
    //lcd.println("SD Card failed");
    u8x8.println(" SD failed      ");
    //    delay(30);
    //    error("Card failed, or not present");                         //Error function displays the error message if SD.begin fails and returns 0
    return;
  }
  Serial.println("card initialized.");                            //If SD.begin is successful
}

void createFile()
{
  //u8x8.setFont(u8x8_font_profont29_2x3_n);
  // create a new file
  char filename[] = "00.CSV";
  for (uint8_t i = 0; i < 200; i++)                               //Make a new file every time the Arduino starts up
  { //Goes from 00 to 199
    filename[0] = i / 10 + '0';
    filename[1] = i % 10 + '0';
    if (!SD.exists(filename))                                     //SD.exists() tests whether a file or directory exists on the SD card
    { //It returns true if the file or directory exists, false if not
      //only open a new file if it doesn't exist
      bhoomiFile = SD.open(filename, FILE_WRITE);                 /*SD.open() opens a file on the SD card. If the file is opened for writing,
                                                                                                                       it will be created if it doesn't already exist (but the directory containing it must already exist).
                                                                                                                        It returns a File object referring to the opened file; if the file couldn't be opened,
                                                                                                                        this object will evaluate to false in a boolean context*/
      //FILE_WRITE enables read and write access to the file
      break;  // leave the loop!
    }
  }

  if (!bhoomiFile)                                                //If file couldn't be opened/created
  {
    error("couldn't create file");
  }
  Serial.print("  Logging to: ");                                   //Otherwise, display the name of the file generated
  Serial.print(filename);
  //u8x8.clear();
  u8x8.setFont(u8x8_font_courR18_2x3_r);
  //u8x8.setCursor(64, 120);
  u8x8.setCursor(-3, 19);
  u8x8.print(filename);

  //u8x8.clear();
  // u8x8.refreshDisplay();
  delay(20);
}

void doTheThing()
{
  DateTime now;

  //delay for the amount of time we want between readings
  delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

  //fetch the time
  now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  Serial.println(timestamp);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print(" , ");

  //now = RTC.now();
  bhoomiFile.print("  ");                  //This space is important. If you remove this, the seconds will not be recorded in the log file
  bhoomiFile.print(now.month(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.day(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.year(), DEC);
  bhoomiFile.print(" ");
  bhoomiFile.print(now.hour(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.minute(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.second(), DEC);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print("");
#if ECHO_TO_SERIAL
  //      Serial.print(now.month(), DEC);
  //      Serial.print("/");
  //      Serial.print(now.day(), DEC);
  //      Serial.print("/");
  //      Serial.print(now.year(), DEC);
  //      Serial.print(" ");
  //      Serial.print(now.hour(), DEC);
  //      Serial.print(":");
  //      Serial.print(now.minute(), DEC);
  //      Serial.print(":");
  //      Serial.print(now.second(), DEC);
  //      Serial.print("");
  //       Serial.print(millis(),DEC);
  //        Serial.print("");
#endif //ECHO_TO_SERIAL
  //Log the voltage reading
  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(scale.get_units() * 1, 4);        //read upto 4 decimal



  if (scale.get_units() < maxi)
  {
    maxi = maxi;
  }
  else if (scale.get_units() >= maxi)
  {
    maxi = scale.get_units();
  }

  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(maxi, 4);      //read upto 4 decimal


  //  bhoomiFile.print(", ");                           //Unit in gram
  //  bhoomiFile.print(m * 1, 4);        //read upto 4 decimal





#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(scale.get_units() * 1, 4);       //read upto 4 decimal
  Serial.print("g ");                           //Unit in gram
#endif //ECHO_TO_SERIAL

  bhoomiFile.println();
  //    #if ECHO_TO_SERIAL
  //      Serial.println();
  //    #endif // ECHO_TO_SERIAL
  u8x8.setFont(u8x8_font_courR18_2x3_r);
  u8x8.setCursor(90, 32);
  //u8x8.print("g,       ");                 //Unit in gram
  u8x8.print("       g ");                 //Unit in gram
  u8x8.print(scale.get_units() * 1, 3);  //read upto 4 decimal point

  // u8x8.setFont(u8x8_font_artossans8_n);
  // u8x8.setCursor(30,0);
  //  u8x8.print("Max ");                 //Unit in gram



#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(maxi, 4);      //read upto 4 decimal
  Serial.print("g ");                           //Unit in gram
#endif //ECHO_TO_SERIAL


  if (Serial.available())
  {
    char temp = Serial.read();
    if (temp == 't' || temp == 'T')
      scale.tare();  //Reset the scale to zero
    if (temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if (temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
  delay(50);

  //When you use file.write(), it doesn't write to the card until you flush() or close().
  //Whenever you open a file, be sure to close it to save your data.
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();
  bhoomiFile.flush();               //flush() ensures that any bytes written to the file are physically saved to the SD card
}

/****************************************************************************************************************/

You should not keep calling scale.get_units(), as this value can change on every call... so what you are writing to the file, may not be the thing you are then comparing to maxi in subsequent code.

  //Log the voltage reading
  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(scale.get_units() * 1, 4);        //read upto 4 decimal

Change the code above to store the result in a variable...

  float currentReading = scale.get_units();
  bhoomiFile.print(currentReading * 1, 4);        //read upto 4 decimal

Then use currentReading in the subsequent code instead of repeatedly calling scale.get_units().

Thanks @red_car. It is working now. But I have got another problem with time. My code saves data in different logger file each time. But the time is not correct. Also in SD card, the time is not correct. Please help me with this issue.

Current code and file screenshots are given here.

//check font here: https://github.com/olikraus/u8g2/wiki/fntlist8x8
//use only one display

#include <Arduino.h>

#include <U8x8lib.h>
//#ifdef U8X8_HAVE_HW_SPI
//#include <SPI.h>
//#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
#include <SD.h>
//#include <Wire.h>
#include "RTClib.h"
#include "HX711.h"  //You must have this library in your arduino library folder
/****************************************************************************************************************/
/****************************************************************************************************************/
/****************************************************************************************************************/
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
//#define SCREEN_WIDTH 128 // OLED display width, in pixels
//#define SCREEN_HEIGHT 64 // OLED display height, in pixels
//#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)

/****************************************************************************************************************/
/****************************************************************************************************************/
/*************************************************VARIABLES******************************************************/
U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE);

/*************************************************VARIABLES******************************************************/
#define DURATION 0.0066667                  //Number of hours, here 2 hours you want this program to run once the button is pressed
#define LOG_INTERVAL 200            //Milliseconds between entries (reduce to take more/faster data)
#define SYNC_INTERVAL 50          // millis between calls to flush() - to write data to the card
uint32_t syncTime = 0;              // time of last sync()
uint32_t start_time;

#define ECHO_TO_SERIAL 1            //Echo data to serial port //Easy method to turn serial printing on and off. Set to 0 if you don't want to print to the Serial Monitor
RTC_DS1307 RTC;                     //define the Real Time Clock object
const int chipSelect = 10;          //for the data logging shield, we use digital pin 10 for the SD cs line
char timestamp[30];
const int pushbutton = 8;
const int done_light = 9;
float m = 0;
float maxi = 0;
/***All the variables for voltage reading function***/
File bhoomiFile;//the logging file

//Hx711 pins:
#define DOUT  3
#define CLK  2
HX711 scale;
//int average = 0;

float calibration_factor = 7311.899902; //7383.399902;//7370.040039; //7370.379882; // for 100g load cell




/****************************************************************************************************************/
/****************************************************SETUP*******************************************************/

                                                        
                                                        void setup()
                                                        {
                                                          scale.begin(DOUT, CLK);
                                                          u8x8.clear();
                                                          Serial.println("Press T to tare");
                                                          scale.set_scale(calibration_factor);  //Calibration Factor obtained from first sketch
                                                          scale.tare();             //Reset the scale to 0
                                                        #if ECHO_TO_SERIAL
                                                          Serial.println("Press button to start");                                //Prompt user to press button
                                                        #endif
                                                          pinMode(pushbutton, INPUT);                 //Set pushbutton as Input
                                                          pinMode(done_light, OUTPUT);                //Set the LED as an output
                                                          digitalWrite(done_light, LOW);              //Make sure the LED is off when we start the program
                                                          Serial.begin(9600);                         //Initialize the serial communication
                                                        
                                                          u8x8.begin();
                                                          u8x8.setFont(u8x8_font_courR18_2x3_r );
                                                          //u8x8.setFont(u8x8_font_amstrad_cpc_extended_r);
                                                        
                                                          delay(100);
                                                        
                                                          while (digitalRead(pushbutton)) {};                                       //Wait for pushbutton input
                                                        #if ECHO_TO_SERIAL
                                                          Serial.println("(BUTTON PRESSED!)");                                    //Once pressed, display a message saying so
                                                        #endif
                                                        
                                                          //delay(1000);                                                              //Display the message for a second
                                                          SD_INIT();
                                                          createFile();
                                                        
                                                          //connect to RTC
                                                          Wire.begin();                                                     //Wire.begin: Initiate the Wire library and join the I2C bus as a master or slave.
                                                          if (!RTC.begin())                                                 //RTC.begin initializes the internal RTC. It needs to be called before any other RTC library methods
                                                          { //Assume that it returns 1 on success and 0 on failure
                                                            bhoomiFile.println("RTC failed");
                                                        #if ECHO_TO_SERIAL
                                                            Serial.println("RTC failed");
                                                        #endif  //ECHO_TO_SERIAL
                                                          }
                                                        
                                                          bhoomiFile.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g), Max weight(g)");        //If RTC initializes successfully...set this as a header in the file
                                                        #if ECHO_TO_SERIAL
                                                          Serial.println("millisecond,Time (MM/DD/YYYY HH:MM:SS), weight (g), Max weight(g)");
                                                        #endif //ECHO_TO_SERIAL
                                                          start_time = millis();              //The very next step after this will be the data recording
                                                          //Therefore, note down the time at this moment as the start time
                                                        }



/****************************************************************************************************************/

/*************************************************LOOP***********************************************************/
void loop()
{
  //Below: As long as current time - start time < required duration, keep recording the data
  for (start_time; (millis() - start_time) < (DURATION * 60 * 60 * 1000L); )
    //To have record time in HOURS: (DURATION * 60 * 60 * 1000L)

   // int maxi = max(scale.get_units(), maxi);

  //  //Log max voltage reading
  
  
  
  
  //m=max(scale.get_units(),m);

  {
    doTheThing();
  }

  u8x8.clear();
  while (1)
  {
#if ECHO_TO_SERIAL
    Serial.println("ALL DONE");           //Once the set amount of time has passed, display message saying so
#endif //ECHO_TO_SERIAL
    digitalWrite(done_light, HIGH);
//    u8x8.setFont(u8x8_font_8x13B_1x2_n);
//    u8x8.print(" Done storing   ");
    u8x8.setFont(u8x8_font_8x13B_1x2_f); // big font
    u8x8.setCursor(0,32);
  //u8x8.print("  g,         ");                 //Unit in gram
  //u8x8.print("M:       ");
  u8x8.print("          g Max   ");                  //Unit in gram
  u8x8.print(maxi, 3);  //read upto 4 decimal point



  u8x8.setFont(u8x8_font_8x13B_1x2_f); // big font
  u8x8.setCursor(0,2);  
  u8x8.print(" Done storing ");  
   u8x8.setCursor(0,5);  
  u8x8.print(" 2 min ");            
 

    
    // u8x8.drawString(1, 1, " Done storing  ");
    //u8x8.drawString(1, 2, " 2 hrs ");
  }
}
/****************************************************************************************************************/

/************************************************FUNCTIONS*******************************************************/

void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while (1);
}

                                                        void SD_INIT()
                                                        {
                                                          Serial.print("Initializing SD card...");
                                                          pinMode(chipSelect, OUTPUT);
                                                        
                                                          //Check if the card is present and can be initialized:
                                                          if (!SD.begin(chipSelect))                                      //SD.begin initializes the SD library and card; Returns 1 on success, 0 on failure
                                                          {
                                                             u8x8.setFont(u8x8_font_courR18_2x3_r);
                                                             //u8x8.setCursor(64, 120);
                                                             u8x8.setCursor(3, 19);                                                   //lcd.println("SD Card failed");
                                                             u8x8.println("No SD");
                                                                                                              //    delay(30);
                                                                                                              //    error("Card failed, or not present");                         //Error function displays the error message if SD.begin fails and returns 0
                                                            return;
                                                          }
                                                          Serial.println("card initialized.");                            //If SD.begin is successful
                                                        }

                                                      void createFile()
                                                      {
                                                                                                                        //u8x8.setFont(u8x8_font_profont29_2x3_n);
                                                        // create a new file
                                                        char filename[] = "00.CSV";
                                                        for (uint8_t i = 0; i < 200; i++)                               //Make a new file every time the Arduino starts up
                                                        { //Goes from 00 to 199
                                                          filename[0] = i / 10 + '0';
                                                          filename[1] = i % 10 + '0';
                                                          if (!SD.exists(filename))                                     //SD.exists() tests whether a file or directory exists on the SD card
                                                          { //It returns true if the file or directory exists, false if not
                                                            //only open a new file if it doesn't exist
                                                            bhoomiFile = SD.open(filename, FILE_WRITE);                 /*SD.open() opens a file on the SD card. If the file is opened for writing,
                                                                                                                       it will be created if it doesn't already exist (but the directory containing it must already exist).
                                                                                                                        It returns a File object referring to the opened file; if the file couldn't be opened,
                                                                                                                        this object will evaluate to false in a boolean context*/
                                                            //FILE_WRITE enables read and write access to the file
                                                            break;  // leave the loop!
                                                          }
                                                        }

                                                  if (!bhoomiFile)                                                //If file couldn't be opened/created
                                                  {
                                                    error("couldn't create file");
                                                  }
                                                  Serial.print("  Logging to: ");                                   //Otherwise, display the name of the file generated
                                                  Serial.print(filename);
                                                  //u8x8.clear();
                                                  u8x8.setFont(u8x8_font_8x13B_1x2_f);
                                                  
                                                  u8x8.setCursor(2,22);
                                                  u8x8.print(filename);
                                                
                                                  //u8x8.clear();
                                                  // u8x8.refreshDisplay();
                                                  delay(20);
                                                }

void doTheThing()
{
  DateTime now;

  //delay for the amount of time we want between readings
  delay((LOG_INTERVAL - 1) - (millis() % LOG_INTERVAL));

  //fetch the time
  now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  Serial.println(timestamp);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print(" , ");

  //now = RTC.now();
  bhoomiFile.print("  ");                  //This space is important. If you remove this, the seconds will not be recorded in the log file
  bhoomiFile.print(now.month(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.day(), DEC);
  bhoomiFile.print("/");
  bhoomiFile.print(now.year(), DEC);
  bhoomiFile.print(" ");
  bhoomiFile.print(now.hour(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.minute(), DEC);
  bhoomiFile.print(":");
  bhoomiFile.print(now.second(), DEC);
  bhoomiFile.print("");
  bhoomiFile.print(millis(), DEC);
  bhoomiFile.print("");
                                          #if ECHO_TO_SERIAL
                                            //      Serial.print(now.month(), DEC);
                                            //      Serial.print("/");
                                            //      Serial.print(now.day(), DEC);
                                            //      Serial.print("/");
                                            //      Serial.print(now.year(), DEC);
                                            //      Serial.print(" ");
                                            //      Serial.print(now.hour(), DEC);
                                            //      Serial.print(":");
                                            //      Serial.print(now.minute(), DEC);
                                            //      Serial.print(":");
                                            //      Serial.print(now.second(), DEC);
                                            //      Serial.print("");
                                            //       Serial.print(millis(),DEC);
                                            //        Serial.print("");
                                          #endif //ECHO_TO_SERIAL
  //Log the weight reading
  bhoomiFile.print(", ");                           //Unit in gram
  float currentReading = scale.get_units();
  bhoomiFile.print(currentReading * 1, 4);        //read upto 4 decimal



  if (currentReading < maxi)
    {
      maxi = maxi;
   }
    else if (currentReading >= maxi)
   {
      maxi = currentReading;
   }

  bhoomiFile.print(", ");                           //Unit in gram
  bhoomiFile.print(maxi,4);       //read upto 4 decimal


  //  bhoomiFile.print(", ");                           //Unit in gram
  //  bhoomiFile.print(m * 1, 4);        //read upto 4 decimal

  u8x8.setFont(u8x8_font_8x13B_1x2_f);//small font
  u8x8.setCursor(0,3);
  //u8x8.print("  g,         ");                 //Unit in gram
  //u8x8.print("M:       ");
  u8x8.print("          g Max   ");                  //Unit in gram
  u8x8.print(maxi, 3);  //read upto 4 decimal point



#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(scale.get_units() * 1, 4);       //read upto 4 decimal
  Serial.print("g ");                           //Unit in gram
#endif //ECHO_TO_SERIAL

  bhoomiFile.println();
  //    #if ECHO_TO_SERIAL
  //      Serial.println();
  //    #endif // ECHO_TO_SERIAL
  u8x8.setFont(u8x8_font_courR18_2x3_r); // big font
  //u8x8.setFont(u8x8_font_inr33_3x6_f);
  u8x8.setCursor(90, 32);
  //u8x8.print("g,       ");                 //Unit in gram
  u8x8.print("         g ");                 //Unit in gram
  u8x8.print(scale.get_units() * 1, 3);  //read upto 4 decimal point

  // u8x8.setFont(u8x8_font_artossans8_n);
  // u8x8.setCursor(30,0);
  //  u8x8.print("Max ");                 //Unit in gram



#if ECHO_TO_SERIAL
  Serial.print(", ");
  Serial.print(maxi, 4);      //read upto 4 decimal
  Serial.print("g ");                           //Unit in gram
#endif //ECHO_TO_SERIAL


  if (Serial.available())
  {
    char temp = Serial.read();
    if (temp == 't' || temp == 'T')
      scale.tare();  //Reset the scale to zero
    if (temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if (temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
  delay(50);

  //When you use file.write(), it doesn't write to the card until you flush() or close().
  //Whenever you open a file, be sure to close it to save your data.
  if ((millis() - syncTime) < SYNC_INTERVAL) return;
  syncTime = millis();
  bhoomiFile.flush();               //flush() ensures that any bytes written to the file are physically saved to the SD card
}

/****************************************************************************************************************/
![Capture1|690x193](upload://g7wSmApGi0tOr6g8oFsy6WYXaia.png)
![Capture2|591x297](upload://tFNbZ1G3jvywKH4GNhbkIJZW7Ca.png)



What do you mean?

Do you mean the timestamp on the files are not correct, or the the times stored in the file are not correct?

Can you provide examples?

Hi @red_car ,

I have attached the files as an example. Both timestamp on the files are not correct and the times stored in the file are not correct.

folder wrong time.pdf (25.2 KB)

09.pdf (70.6 KB)

Could you also provide the output from the Serial Monitor, from when the program starts.

Hi @red_car, I attached the serial monitor output. Really appreciate your help.
serial snip.pdf (14.4 KB)

What I was after was the debug messages when the program first starts up.

Hi @red_car,
I have attached debug messages and serial monitor output from the beginning.
debug_message.pdf (8.9 KB)
serial_output.pdf (18.0 KB)

Can you run the Library Example code for RTClib.h and see correct times?

Yes, I ran timestamp and I see correct time in serial monitor. After I run this timestamp code, my code saves time correctly inside csv file. But once the power gets disconnected and connected again, code outputs wrong time again

Do you have a battery in the RTC module? Try changing for a new one.

Your first order of business is to get the RTC module working correctly between power cycles.

I tried to use another batteries. But it did not help.
Only time Date time correct is, when I run timestamp code. But again timing is wrong with unplugging from power.

Please post the Serial output you see when you run the RTClib.h library example DS1307.ino.

Thanks for your response. Here I have attached the serial output from ds1307.ino
ds1307.pdf (90.9 KB)

The file you attached shows both the correct time now and the correct time in the future.

Why do you think that 2022/10/11 3:47:22 is not 7days, 12 hr 30min and 6 seconds in the future from 2022/10/3 (Monday) 15:17:16.?

Ohh, I see. Yap, its right.

But I do not understand where is the actual problem. Is it my code or something else?