Setting time on RTC -- your comments?

I have written some code to manually set the time on an RTC.
I modified it from code that I had used successfully in the past. I modified it so as to handle the conversion to BCD automatically, as well as automatically calculate the correct day of the week.

This version of the code Has Not Been Tested, and I don’t have proper hardware handy, so please let me know what you think of this code.

The reason I wrote the day-of-week function is this: I have seen timepieces (online and in real life) where you have to set the year, month, day of the month, …, and also the day of the week. It is less work for everyone if the correct day of the week is calculated automatically. It is also a useful check in case the date is set incorrectly. (People are generally more aware of the day of the week than they are of the exact date.)

Please let me know what you think of this code.

clock_time_adjust_user_friendly_no_div.ino (2.88 KB)

The days of the week appears to work using this code in setup():

void setup() {
  char days[][4] = {"   ", "Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
  int timeset[] = {2014,  12,  11,  0,  0,  0};
                // year  mo day  hr min sec
  Wire.begin();
  Serial.begin(9600);
  // program to precisely set Chronodot
  
  Serial.println(toBCD(timeset[5])); // seconds
  Serial.println(toBCD(timeset[4])); // minutes
  Serial.println(toBCD(timeset[3])); // hours
  Serial.println(days[weekday(timeset[0],timeset[1],timeset[2])]); // day of week
  Serial.println(toBCD(timeset[2])); // day of month
  Serial.println(toBCD(timeset[1])); // month
  Serial.println(toBCD(timeset[0])); // year

}

However, the last three Serial object print calls don’t look right. Also, why waste the unused slot in the days[] array?

The RTC uses binary-coded decimal, not straight binary.
Here is a brief explanation of binary versus binary-coded decimal.
(BCD = binary-coded decimal)

Binary: bits are valued 128, 64, 32, 16, 8, 4, 2, 1
   BCD: bits are valued  80, 40, 20, 10, 8, 4, 2, 1

Dec   binary      BCD
---  --------  --------
  0  00000000  00000000
  1  00000001  00000001
  2  00000010  00000010
...  ........  ........
  7  00000111  00000111
  8  00001000  00001000
  9  00001001  00001001
 10  00001010  00010000
 11  00001011  00010001
...  ........  ........
 15  00001111  00010101
 16  00010000  00010110
...  ........  ........
 19  00010011  00011001
 20  00010100  00100000
...  ........  ........
 99  01100011  10011001

If you try to print a BCD number the way you would print an ordinary number, it will come out wrong.
Try printing it as HEX and see what you get.