How to Request time from RTC 1307

Searched the web, for days and days. there are no clear cut answers. Everyone teaches “How to upload the RTC library”. I have already set the time of the RTC1307, now i just want to know if there is a function that i can call to import the time to the Arduino and basically sync with it everytime it resets.
If it’s not necessary to import the time, and the Arduino does that automatically then i would like to know the function by which i can tell Arduino to display it on the serial monitor or the i2c lcd display. by seeing the example codes, i doubt there is going to be a single line function which does all of that. but if someone could guide me as to how to actually prompt the RTC to send time atleast, then that would be awesome for us beginners.
My project involves keeping the time, showing the time on demand and starting a countdown for 21 days after pressing a button which the Arduino should remember, the time left and time past from the trigger event until the time period of 21 days has passed.
I know it is a lot to ask for but just to give you guys the feel of the entire situation i gave a little more information than needed so that you guys could help me keeping this in mind.

UPDATE- SUCCESS:

Thanks to this forum and passionate people who put up with my noobness i finally figured out a piece of code that does what i wanted. and obviously hours and hours of reading. for people who have the same problem or want to go down the same path as me this is the code i came up with.

#include <Wire.h>    //wire library
#include <LiquidCrystal_I2C.h>    //i2c lcd library
LiquidCrystal_I2C lcd(0x3F, 16,2);      //lcd address rows and cols
int s;     //bucket for seconds
int mn;    //bucket for mins
int hr;   //bucket for hour
int DayOfTheWeek;  //day of the week
int Mon;     //cucket for month 
int yr;     //bucket for year
int d;     //bucket for day
const int pin=7;    //pin number
int buttonState;    //either high or low button state 
int lastButtonState;     //records last button state trying to come with a way to activate certain function by judging the time they have it ON

//maybe create seperate functions to show date and time seperately

void setup() {
Wire.begin();     //starts the wire communication
Serial.begin(9600);   //sets up the serial monitor for debugging
lcd.init();   //lcd starting command
lcd.init();    //lcd starting command
lcd.clear();    //lcd clear with every reset
lcd.backlight();   //turns on the backlight
  }


void loop() {
  buttonState=digitalRead(pin);     //puts the read of the button either high or low into the button state variable
  if(buttonState==HIGH) {      //if the button is pressed then carry out the following instructions
  ShowTime();     //show time on the first row
  ShowDate();     //show date on the second 

   // will show the time as long as the delay has not expired specified in the function
};

__________________ Functions in a different tab make it little bit tidy

//____________Get time and set each variable to it in setup 
void ShowTime() {
  Wire.beginTransmission(0x68);     //address 
  Wire.write(0x00);  //register the next ones are going to be automatically selected apparently 
  Wire.endTransmission();
  Wire.requestFrom(0x68, 7);
  s= (bcdToDec(Wire.read() & 0x7f));
  mn= (bcdToDec(Wire.read()));
  hr= (bcdToDec(Wire.read() & 0x3f));     //settings all the reads to corresponding variable to be used
  DayOfTheWeek=(bcdToDec(Wire.read()));
  d=(bcdToDec(Wire.read()));
  Mon= (bcdToDec(Wire.read()));
  yr=(bcdToDec(Wire.read())+2000);
  lcd.setCursor(0,0);
  lcd.print("Time: ");
  lcd.print(hr);
  lcd.print(":");
  lcd.print(mn);
  lcd.print(":");
  lcd.print(s);
};

//---show date function
void ShowDate() {
 Wire.beginTransmission(0x68);     //address 
  Wire.write(0x00);  //register the next ones are going to be automatically selected apparently 
  Wire.endTransmission();
  Wire.requestFrom(0x68, 7);
  s= (bcdToDec(Wire.read() & 0x7f));
  mn= (bcdToDec(Wire.read()));
  hr= (bcdToDec(Wire.read() & 0x3f));
  DayOfTheWeek=(bcdToDec(Wire.read()));
  d=(bcdToDec(Wire.read()));
  Mon= (bcdToDec(Wire.read()));
  yr=(bcdToDec(Wire.read()));
  lcd.setCursor(0,1);
  lcd.print("Date: ");
  lcd.print(d);
  lcd.print(":");
  lcd.print(Mon);
  lcd.print(":");
  lcd.print(yr);
  delay(1000);
};


//important bcd to dec functions

byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
};


void testBlink() {
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13,LOW);
    delay(100);
  };

This was an amazing experience. hope i didn’t annoy anyone :slight_smile:

If you have not chosen a library, install one and look at the included example sketches.

If you have chosen a library, use that library to fetch the current time. Some will return a string ready to print. Some rely on the Time library for formatting a string to print.

If you don't want to use a library and want to address the chip hardware, study the datasheet for the chip.

Yes. I have a library but i don't enjoy using any one else's code. i want to be able to do basic things such as this on my own. importing and a uploading the same sketch to the arduino everytime i want to see the time is going to be time consuming.
I am searching for a site where i can learn the Wire library and being able to write and read from chips with your own code kinda turns me on. any suggestions are welcome. Thanks for the data sheet tip. :slight_smile:

One of the better books I've found is Arduino Internals by Dale Wheat. This is an in-depth look at bypassing most of the Arduino shell and getting down to bare metal. As for the DS1307, it's just an I2C peripheral. You can't get 'down to the chip' unless you remove it from the component board it currently is soldered to. You certainly can however, talk to it through SDA and SCL without the use of a library, just learn its language. As John said, get the datasheet. Get datasheets on everything, they rarely change.

Take the bits out of here that read the RTC, make it a function in your program

/*
Test of RTC DS1307 via I2C.
 Counts 
 Seconds, 
 Minutes, 
 Hours, 
 Date of the Month, 
 Month, 
 Day of the week, and 
 Year with Leap-Year
 
 56 bytes battery backed RAM
 Square Wave Output
 
 11/17/2012- Updated for Wire.write & Wire.read commands
 1/18/13 - fixed unclear reference to 0x00
 */


/*
Modified to Run thru IDE Serial port
*/
#include <Wire.h>


//variables
byte zeroByte = 0;
byte seconds_address = 0x00;
byte seconds; // bit 7 = Clock Halt, Enabled = 0, Halt = 1
// bits 6-5-3 = tens of seconds 0-6,  bits 3-2-1-0 = units of seconds, 0-9


byte minutes_address = 0x01;
byte minutes;  // bits 6-5-4 = tens of minutes, bits 3-2-1-0 = units of minutes


byte hours_address = 0x02; 
byte hours;  // 7=0. 6 = 1 for 12 hr, 0 for 24 hr.
// bit 5: 12 hr mode = AM(0)/PM(1). 24 hr mode = upper tens of hrs
// bit 4 =  lower tens of hrs, bits 3-2-1-0 = units of hours (0-9)


byte day_week_address = 0x03; 
byte day_week = 0; // range 01-07


byte date_month_address = 0x04;
byte date_month = 0; // range 01-31


byte month_address = 0x05;
byte month = 0; // range 01-12


byte year_address = 0x06;
int year = 0; // upper byte 0-9, lower byte 0-9


byte square_address = 0x07;
byte sqwe = 0;  // square wave enable
// Out-0-0-Sqwe-0-0-RS1-RS0
// Out, Sqwe = 0/0 - Square wave output = 0
// Out, Sqwe = 1/0 - Square wave output = 1
// Out, Sqwe = 0/1 or 1/1 - Square wave output per RS1/RS0
// RS1/RS0 = 00 = 1 Hz
// RS1/RSo = 01 = 4 KHz
// RS1/RS0 = 10 = 8 KHz
// RS1/RS0 = 11 = 32 KHz


byte RTC_ram_address = 0x08; //range = 08-63, 0x08-0x3F


int RTC_address = 0x68; // 1101 000 


byte incomingCommand = 0;
byte RTC_write_command = 0;
byte RTC_read_command = 0;
byte RTC_ram_command = 0;


// use F0xx, F1xx,F2xx, F3xx, F4xx, F5xx, F6xx, F7xx
// to send one register write commands
// use E0xx to read registers back - not coded yet
// use C0xx to read RAM back - not coded yet


byte incomingRegister = 0;
byte RTC_register = 0;
byte incomingData1 = 0;
byte incomingData2 = 0;
byte new_data = 0;
byte outgoingData = 0;
int delay_time = 100;


unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long duration = 5000;


void setup() {
  Wire.begin(); // no address, we are master
  Serial.begin (57600);  
  Serial.flush();
  currentMillis = millis();  
}


void loop() {


  if (Serial.available() >3){
    incomingCommand = Serial.read();
    incomingRegister = Serial.read();
    incomingData1 = Serial.read();
    incomingData1 = incomingData1 - 0x30; // convert ASCII to HEX
    incomingData2 = Serial.read();
    incomingData2 = incomingData2 - 0x30;  // convert ASCII to HEX
    new_data = (incomingData1 << 4) + incomingData2;  // put the Upper/Lower nibbles together
    Serial.print ("command ");
    Serial.println (incomingCommand);
    Serial.print ("register ");
    Serial.println(incomingRegister);
    Serial.print ("data1 ");
    Serial.println (incomingData1, HEX);
    Serial.print ("data2 ");
    Serial.println (incomingData2, HEX);
    Serial.print ("combined data ");    
    Serial.println (new_data, HEX);
    
  }
  // *******************************************
//  RTC_write_command = incomingCommand & 0xF0;  // mask off high byte
//  if (RTC_write_command == 0xF0){  // check for Write command
if ((incomingCommand == 'F') | (incomingCommand == 'f')){
  incomingCommand = 0;  // reset for next pass
//    RTC_register = incomingCommand & 0x0F;  // mask off low btye
//    incomingCommand = 0;
//    new_data = incomingData;
    Serial.println (" Sending a command ");
//    switch (RTC_register){
switch (incomingRegister){
  case '0': // write seconds
        Serial.println ("Seconds ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(seconds_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
      delay (delay_time);
      break;
    case '1': // write minutes
    Serial.println ("Minutes ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(minutes_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
      delay (delay_time);
      break;
    case '2': // write hours
        Serial.println ("Hours ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(hours_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '3': // write day
        Serial.println ("Day ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(day_week_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '4': // write date of month
        Serial.println ("Day of Month ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(date_month_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '5': // write month
        Serial.println ("Month ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(month_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '6': // write year
        Serial.println ("Year ");
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(year_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '7': // write square wave
        Serial.println ("Square Wave ");
    Serial.println (RTC_register, HEX);
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(square_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
    case '8': // write RAM
        Serial.print ("RAM ");
    Serial.println (RTC_register, HEX);
      Wire.beginTransmission(RTC_address); // select device
      Wire.write(RTC_ram_address);          // queue the register
      Wire.write(new_data);                  // queue data
      Wire.endTransmission();            // send it
     delay (delay_time);
      break;
      // all others,do nothing
      Serial.println ("Invalid command ");
    }  // end Switch
  } // end if command == 'F'
  // ************************************


  currentMillis = millis();
  if ( (currentMillis - previousMillis) >= duration){
    previousMillis = currentMillis;  
    // Reset the register pointer  
    Wire.beginTransmission(RTC_address);  
    Wire.write(zeroByte);  
    Wire.endTransmission();   


    Wire.requestFrom(RTC_address,8 );  
    seconds = Wire.read();  
    minutes = Wire.read();  
    hours = Wire.read();  
    day_week = Wire.read();  
    date_month = Wire.read();  
    month = Wire.read();  
    year = Wire.read();  
    sqwe = Wire.read();


    // Seconds 
    // bit 7 = Clock Halt, Enabled = 0, Halt = 1
    // bits 6-5-3 = tens of seconds 0-6,  bits 3-2-1-0 = units of seconds, 0-9 


    // Hours
    // 7=0. 6 = 1 for 12 hr, 0 for 24 hr.
    // bit 5: 12 hr mode = AM(0)/PM(1). 24 hr mode = upper tens of hrs
    // bit 4 =  lower tens of hrs, bits 3-2-1-0 = units of hours (0-9)


    Serial.print ("Hrs " );
    Serial.print (hours, HEX);
    Serial.print (" Mins ");
    Serial.print (minutes, HEX);
    Serial.print (" Secs ");
    Serial.print (seconds, HEX);
    Serial.print (" Day ");
    Serial.print (day_week, HEX);
    Serial.print (" Date ");
    Serial.print (date_month, HEX);
    Serial.print (" Month ");
    Serial.print (month, HEX);
    Serial.print (" Year 20");
    Serial.print (year, HEX);
    Serial.print (" Square Wave ");
    Serial.println (sqwe, HEX);


  }
}

You cannot read the time in a single line – not unless you write your own function to do that, and the code for that function will be at least a few lines long.

Do you know what “binary coded decimal” is? Your RTC keeps track of the numbers in the time and date using binary-coded decimal, which is different from the binary numbers your Arduino is built to work with. It is possible to write code to make the Arduino count in binary-coded decimal: this is the approach I prefer because it fits my sense of humor. However, this is not the normal approach. The normal approach is to convert binary-coded decimal to binary so that the Arduino can then deal with the numbers the same way it would deal with any other numbers.

My explanation of the difference between binary and binary-coded decimal is here:

If you’re not quite sure how binary works, this video explains several systems for representing numbers, one of which is the binary system:

If you want some “low level” code to set and/or read the time, here is something I just put together for you:

(WARNING: because this is not 100% identical to code I’ve already tested, it might be buggy. But I’m guessing it will probably work well enough.)

(UPDATE: I now know that this code will not behave as I intended. I made some mistakes, mainly about variable scope. Please see reply #14 in this thread for an update.)

#include "Wire.h"

// variables to hold the numbers for the time and date
uint8_t ss=0x00;
uint8_t mi=0x00;
uint8_t hh=0x00;
uint8_t wd=0x06;
uint8_t dd=0x01;
uint8_t mo=0x01;
uint8_t yy=0x00;

void setup() {
  Wire.begin();
  Serial.begin(9600); // or whatever baud rate you are using 
  
  /*
  
  // If you need to set the Chronodot, uncomment this section. 
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x00); // select register
  // NOTE: if you wish to correctly set the Chronodot,
  // you *must* change the following numbers to the correct time!
  // (plus 20 seconds or so to allow for compilation, etc.)
  Wire.write(0x30); // seconds (BCD)
  Wire.write(0x43); // minutes (BCD)
  Wire.write(0x17); // hours (BCD)
  Wire.write(0x07); // day of week (I use Mon=1 .. Sun=7)
  Wire.write(0x15); // day of month (BCD)
  Wire.write(0x09); // month (BCD)
  Wire.write(0x13); // year (BCD, two digits) 
  Wire.endTransmission();
  
  */
}

void loop() {
  delay(500);

  // send request to receive data starting at register 0
  Wire.beginTransmission(0x68); // 0x68 is DS3231 device address
  Wire.write((uint8_t)0); // start at register 0
  Wire.endTransmission();
  Wire.requestFrom(0x68, 7); // request seven bytes (ss, mi, hr, wd, dd, mo, yy)

  if (Wire.available() >= 7)
  {
    byte ss = Wire.read(); // get seconds
    byte mi = Wire.read(); // get minutes
    byte hh = Wire.read(); // get hours
    byte wd = Wire.read();
    byte dd = Wire.read();
    byte mo = Wire.read();
    byte yr = Wire.read();

    Serial.print ("\'");
    if (yr<0x10) Serial.print("0"); Serial.print(yr,HEX); Serial.print("-");
    if (mo<0x10) Serial.print("0"); Serial.print(mo,HEX); Serial.print("-");
    if (dd<0x10) Serial.print("0"); Serial.print(dd,HEX); Serial.print("(");
    switch (wd) {
      case 1: Serial.print("Mon"); break;
      case 2: Serial.print("Tue"); break;
      case 3: Serial.print("Wed"); break;
      case 4: Serial.print("Thu"); break;
      case 5: Serial.print("Fri"); break;
      case 6: Serial.print("Sat"); break;
      case 7: Serial.print("Sun"); break;
      default: Serial.print("Bad");  
    }
    Serial.print(") ");
    if (hh<0x10) Serial.print("0"); Serial.print(hh,HEX); Serial.print(":");
    if (mi<0x10) Serial.print("0"); Serial.print(mi,HEX); Serial.print(":");
    if (ss<0x10) Serial.print("0"); Serial.print(ss,HEX); Serial.println("");   
  }  
  else {
    Serial.println("Unable to read time from RTC!");
  }
}

http://bildr.org/2011/03/ds1307-arduino/
might be of use

WHOA!!! Thanks for taking the time to reply with such great depth. Some have even written codes for me. this was unexpected. I will certainly check and try all of them out. it cleared a bunch for me.
Thanks a million.

CrossRoads:
Take the bits out of here that read the RTC, make it a function in your program

Hmm i just looked at the code certainly is long and complex (for me) it will take me a while to understand that. this just made me realize that we sending and getting data from chips is not easy.

Thank you.

Nick_Pyner:
bildr Do You Have The Time? DS1307 RT Clock + Arduino - bildr
might be of use

Helped indeed. Thanks. :slight_smile:

I am searching for a site where i can learn the Wire library and being able to write and read from chips with your own code kinda turns me on. any suggestions are welcome. Thanks for the data sheet tip.

More for you!! Please, follow/read the comments placed against the instructions to understand the meaning and reason for writing this instruction. the program has totally excluded the Library Functions; but, it has utilized the commands of the I2C protocol.

We will be frequently consulting the following two diagrams – Register Map of RTC1307 and the Clcok System Block diagram,

Figure-1: Register map of RTC1307 RTC


Figure-2: DS1307 RTC Based Clock System

A: Let us first operate the RTC in 24-Hrs Clock Mode with an initial arbitrary Time :

#include <Wire.h>     //needed because DS3231 uses I2C Bus
#include<LiquidCrystal_I2C.h>  //neded by LCD
LiquidCrystal_I2C lcd(0x27, 16, 2); //lcd address; 16 characters 2 line

#define deviceAddress 0x68    //I2C Bus address of RTC
#define secRegAdr 0x00        //this is not I2C bus address; this is internal address of Sec Register

void setup()
{
  //-------initialize I2C LCD using Library functions------------
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);

  //-----initialize I2C BUs at default speed---------------------
  Wire.begin();
  
  //----intialize RTC1307 with 24-hrs Clock. Say, Intial Time: 23 : 58 : 17(hrs:min:sec)
  Wire.beginTransmission(deviceAddress);  //queuing address, data direction bit in buffer
  Wire.write(secRegAdr);                     //pointing Second Register and queuing it
  Wire.write(0x17);  //17-sec (in BCD format) to be written in SecRegister; queing
  Wire.write(0x58); //58-min(in BCD format) to be automatically wrirtten into MinReg; queuing
  Wire.write(0x23); //23-hrs (in BCDformat) to be aut written into HrsReg; queuing
  Wire.endTransmission(); //all queued data written into Time Regs of RTC on handshaking

  //------Clock has already statrted------
  //----- now read time and show it on the bottom line of LCD
}

void loop()
{
  showTimeOnLCD();
}  

void showTimeOnLCD()
{
  //-----Read back the Time from RTC and show on Bottom Line of LCD--------------------
  Wire.beginTransmission(deviceAddress); //START, Roll Cal
  Wire.write(0x00); //set SEC Register; others registers will be auto accessed
  Wire.endTransmission(); //Execute the above queued data, ACK, STOP

  //-------Requesting Time from the RTC; Time is saved in a 32-byte wide FIFO buffer---------
  Wire.requestFrom(deviceAddress, 3);   //SEC, MIN, and HRS to read from RTC as BCD
  byte bcdSeconds = Wire.read();        //Current Second in the variable bcdSeconds in BCD format
  byte bcdMinutes = Wire.read();
  byte bcdHours = Wire.read();

  //---------------------------------------------------------------------------------------------
  lcd.setCursor(0, 1);      //cursor position at the beginning of bottom line
  lcd.print("Time = ");
  //show HRS--
  lcd.write((bcdHours>>4) + 0x30);  //shifting and making ASCII codes
  lcd.write((bcdHours & 0x0F) + 0x30);
  lcd.write(':');
  
  //show MIN--
  lcd.write((bcdMinutes>>4) + 0x30);
  lcd.write((bcdMinutes & 0x0F) + 0x30);
  lcd.print(':');
 
 //shiw SEC
 lcd.write((bcdSeconds>>4) + 0x30);
 lcd.write((bcdSeconds & 0x0F) + 0x30);
}

B: Now, you have got a stating point. You can slowly add the following features Like:
(1) Even you reset the UNO, the intial set time will never be changed.
(2) You can set the Data (yrs/mo/day) and show it on the Top Line of LCD.
(3) You can set 12-hrs time by consulting Fig-1.
(4) You can put the LCD/MCU on sleep. When you will press K1, the LCD will show the current date and Time.

(5) You can also implement your decrement function? How? the RTC is always clocking up and not down?

Any query for questions/clarifications are welcome!

GolamMostafa:
(5) You can also implement your decrement function? How? the RTC is always clocking up and not down?

hmm... i think it would be ideal if i make a function that would have a for loop inside and delay will be 24 hours which will complete one cycle and then make a trigger for example with a press of a button reset value to 22 and decrement with 24 hour delay however this would be useless without the arduino actually remembering which number it was on the last time it turned off. so i thought about making a last recorded variable or maybe the for loop variable can be used itself. the variable will be stored in the eeprom of the arduino which with every wake up gets the value and resume the count from that. i make it sounds easy but i am kinda scared that it is going to take a lot of coding.

so that was my plan i came up with yesterday.

anyway. your code really helped cause of the comments. however there are some statements where the comment is missing if you don't mind could you clear it for me?

Lets for a second forget i am trying to display it to the lcd cause that makes it a little complicated for me. i want to start slow. i understand from the i2C bus system that i first have to send a call to the slave device which is the i2c address set to 0x68.. after that i have to select the register and then express how many bytes i want.. and after expressing that i will have to request the bytes and next step is the rtc stores in bcd so once the data is send i have to convert it to bcd. i hope i am on point till here and you are with me.

If i write the the most basic sketch which does only that. after trying, i came up with this:

I am trying to only read from the clock since it is already set. however if i understand the code i can also set it later without library btw will writing the code without library consume less space on the flash? moving on..

#define rtcAddress 0x68    //i am setting the the slave device address to send right after establishing wire 
                                        //  connection

#define secRegister 0x00  //defining the secs register in the slave device. from the datasheet i understand 
                                       //that this is the sec register.my question is don't i have to define each register? 
                                      // sec, hours, mins, etc?  

voide setup() {
 
Wire.begin();  //establishing a connection line between i2c device at default speed

serial.begin(9600);  //starting serial monitor to view the data for simplification purpose

Wire.beginTransmission(rtcAddress);   //sending out the address frame/bits to the slave device. if it is true 
                                                        // the slave device will send out an ack bit (if i am not wrong)

wire.write(secRegister);    //in here you are i believe writing to it does it work like if i start a write 
                                       //transmission it will also read from it? 

//And you said the other register are auto selected. i am referring to the (reading time from rtc part of //code) and then 

Wire.endTransmission(); //you said that it executes all the queued processes are going to be executed. so //does that mean if i dont want to set the time again n again i will still have to set it anyway? if for example //i dont queue those writing to the registers i can't select the seconds register? i am sorry i am little //confused here. 



lcd.write((bcdHours>>4) + 0x30);  // i am not sure how this converts bcd to decimal and what that 0x30 is

lcd.write((bcdHours & 0x0F) + 0x30);  //this confuses me even more if the above commands converts it //and display it do not know what this does. could it be that these are the lcd addresses? since you included //it in your code?



//i am forced to use the wire library now since whenever i try to print the time to it sometimes my code //works which works with the rtc library but sometimes it does not.

my current code is.

void setup() {
  // put your setup code here, to run once: 
  
  Serial.begin(9600); //estalblishes connection
  rtc.begin(); //starts rtc  (built in function in library)
  lcd.init(); 
  lcd.init();
  lcd.clear();
  }
void loop() {

  DateTime now = rtc.now();      //built in function necessary do not know why
  lcd.setCursor(0,0);    //setting starting cursor point 
  lcd.print("Time = ");   //printing the string time
  h= now.hour();        //puts the hour functions value into h local variable which 
  m= now.minute();      //puts into m 
  s= now.second();      //same 
  lcd.print(h);
  lcd.print(":");     
  lcd.print(m);       //printing the variables value whatever it is to the serial monitor
  lcd.print(":");
  lcd.print(s);
  delay(1000);     //the started to show flow like effect in lcd it kinda scrolled from top to bottom so i added 
                            this delay. 
  lcd.clear();       //clears the lcd to not print it again n again
  
}

I know this code is really bad this is like my first try ever. if you guys could suggest how to improve the code that would be awesome. also i tried to make a function out of this but i can't seem to figure out how i can print a single line which would contain all the variables in it.

My function looks the same as above which did not work. i am so embarrassed to share this but i guess that is how you learn. NOTE: i have no coding experience except digitalWrite(13, HIGH); XD

it does work when i type it like the above code. but when i try to call the function like this

Serial.print(ShowTime());

also i think it will be better to stick this function into a variable and then call it but i just do not know how to put 3 variables into a single variable.

My function:

void ShowTime() {               //handy little function custom made to just  call upon the rtc request time as 
  h, s, m and puts it into some variables to be used later
  DateTime now = rtc.now();      //built in function necessary do not know why
  lcd.print("Time = ");
  h= now.hour();        //puts the hour functions value into h variable 
  m= now.minute();      //puts into m 
  s= now.second();      //same 
  lcd.print(h);
  lcd.print(":");     
  lcd.print(m);       //printing the variables value whatever it is to the serial monitor
  lcd.print(":");
  lcd.print(s);
  
  }

odometer:
(WARNING: because this is not 100% identical to code I've already tested, it might be buggy. But I'm guessing it will probably work well enough.)

Thanks for the reply. i first tried to copy and paste the code looked fine to me. but it didn't work. why not link me to your full code?

UPDATE:
i read all the comments took bits and pieces out of everyones comment and came up with this

code:

#include <Wire.h>

void setup() {

Wire.begin();
Serial.begin(9600);
}


void loop() {
  Wire.beginTransmission(0x68);     //address 
  Wire.write(0x00);  //register the next ones are going to be automatically selected apparently 
  Wire.endTransmission();
  Wire.requestFrom(0x68, 7);
  Serial.print(bcdToDec(Wire.read() & 0x7f));
  Serial.print(" seconds, ");
  Serial.print(bcdToDec(Wire.read()));
  Serial.print(" minutes, ");
  Serial.print(bcdToDec(Wire.read() & 0x3f));
  Serial.print(" hours, ");
  Serial.print(bcdToDec(Wire.read()));
  Serial.print(" day of week, ");
  Serial.print(bcdToDec(Wire.read()));
  Serial.print(" day, ");
  Serial.print(bcdToDec(Wire.read()));
  Serial.print(" month, ");
  Serial.print(bcdToDec(Wire.read())+2000);
  Serial.println(" year");
delay(1000);
};

byte bcdToDec(byte val)
{
  return ( (val/16*10) + (val%16) );
};

However i am still not sure what this “0x7f” and “0x3f” mean.

my mistakes in previous code according to me:

1-I did not make that bcdToDec function which could convert the values to dec
and a little itsy bitsy mistakes here and there XD

This is the minimum that i could make it. but it still uses 6,148 bytes of the total 28kb(using leonardo) memory. with this pattern i do not think i will be able to write all of my code inside it. there must be some tricks to it… cause i saw a 300 to 400 line code that used only 28kb mines going to be smaller but i have to learn how to do that.

Again Thanks all!

How ever i still do not

manhoosbilli1:
Thanks for the reply. i first tried to copy and paste the code looked fine to me. but it didn’t work.

What happened when you tried it? Did it compile? How exactly did it “not work”?

As it stands, I see now that I made some mistakes, most of which related to variable scope. I have (hopefully) corrected them below:

#include "Wire.h"

// variables to hold the numbers for the time and date
uint8_t ss=0x00;
uint8_t mi=0x00;
uint8_t hh=0x00;
uint8_t wd=0x06;
uint8_t dd=0x01;
uint8_t mo=0x01;
uint8_t yy=0x00;

void setup() {
  Wire.begin();
  Serial.begin(9600); // or whatever baud rate you are using
  
  /*
  
  // If you need to set the Chronodot, uncomment this section.
  Wire.beginTransmission(0x68); // address DS3231
  Wire.write(0x00); // select register
  // NOTE: if you wish to correctly set the Chronodot,
  // you *must* change the following numbers to the correct time!
  // (plus 20 seconds or so to allow for compilation, etc.)
  Wire.write(0x30); // seconds (BCD)
  Wire.write(0x43); // minutes (BCD)
  Wire.write(0x17); // hours (BCD)
  Wire.write(0x07); // day of week (I use Mon=1 .. Sun=7)
  Wire.write(0x15); // day of month (BCD)
  Wire.write(0x09); // month (BCD)
  Wire.write(0x13); // year (BCD, two digits)
  Wire.endTransmission();
  
  */
}

void loop() {
  delay(500);

  // send request to receive data starting at register 0
  Wire.beginTransmission(0x68); // 0x68 is DS3231 device address
  Wire.write((uint8_t)0); // start at register 0
  Wire.endTransmission();
  Wire.requestFrom(0x68, 7); // request seven bytes (ss, mi, hr, wd, dd, mo, yy)

  if (Wire.available() >= 7)
  {
    ss = Wire.read(); // get seconds
    mi = Wire.read(); // get minutes
    hh = Wire.read(); // get hours
    wd = Wire.read();
    dd = Wire.read();
    mo = Wire.read();
    yy = Wire.read();

    Serial.print ("\'");
    if (yy<0x10) Serial.print("0"); Serial.print(yy,HEX); Serial.print("-");
    if (mo<0x10) Serial.print("0"); Serial.print(mo,HEX); Serial.print("-");
    if (dd<0x10) Serial.print("0"); Serial.print(dd,HEX); Serial.print("(");
    switch (wd) {
      case 1: Serial.print("Mon"); break;
      case 2: Serial.print("Tue"); break;
      case 3: Serial.print("Wed"); break;
      case 4: Serial.print("Thu"); break;
      case 5: Serial.print("Fri"); break;
      case 6: Serial.print("Sat"); break;
      case 7: Serial.print("Sun"); break;
      default: Serial.print("Bad");  
    }
    Serial.print(") ");
    if (hh<0x10) Serial.print("0"); Serial.print(hh,HEX); Serial.print(":");
    if (mi<0x10) Serial.print("0"); Serial.print(mi,HEX); Serial.print(":");
    if (ss<0x10) Serial.print("0"); Serial.print(ss,HEX); Serial.println("");  
  }  
  else {
    Serial.println("Unable to read time from RTC!");
  }
}

odometer:

it compiled, but did not show any results if i am not forgetting. though i have been successful in making a function that call on time but i still wanna ask. what do you mean by 0x10? “if (hh<0x10)”

manhoosbilli1:
why not link me to your full code?

I have written several versions of this sort of thing. Here is one:
(two sketches, one to set the time and another to read it and show it on the Serial monitor)

Here is another:
(sketch to read the time and display it on an LCD)

Here is yet another:
(an insane, and ambitious, chiming clock -- do you have a speaker, or at least a piezo buzzer?)

odometer:
(an insane, and ambitious, chiming clock -- do you have a speaker, or at least a piezo buzzer?)

hmm.. checked them out. they were awesome. looks like you know what you are doing. i have been up all night trying to find a solution to another task that i want achieve but haven't been able to word it properly hence no results. Do you prefer that i make another post or message you? or maybe just reply here? i am sure it will require a long explanation.

manhoosbilli1:
it compiled, but did not show any results if i am not forgetting.

What Serial baud rate were you using?

though i have been successful in making a function that call on time but i still wanna ask. what do you mean by 0x10? “if (hh<0x10)”

The 0x means hexadecimal. So, for example 0xFF is 255, which was the most rupees Link could carry in the original Zelda game.

manhoosbilli1:
hmm.. checked them out. they were awesome. looks like you know what you are doing.

It helps when you have the right hardware to actually test things out. Right now, I don't have the hardware for testing, which means that mistakes are more likely to get through.

i have been up all night trying to find a solution to another task that i want achieve but haven't been able to word it properly hence no results. Do you prefer that i make another post or message you? or maybe just reply here? i am sure it will require a long explanation.

Please reply here.

If you are not sure how exactly to explain what you want, it would at least help to give examples of how you want it to behave.