+
+#if I2C
+
+; ----------------------------------------------
+; Set software clock from hardware clock
+
+rtc_get:
+ push _0 ;Placeholder for month/weekday
+ push _0 ;day/year
+ push _0 ;hours
+ push _0 ;minutes
+ ldi temp,0x10 ;register address
+ push temp ;save reg adr/placeholder for sec
+ in zh,sph
+ in zl,spl
+ ldi temp,0xA0 ;PCF8583 slave address
+ push temp
+
+ ldi temp2,2
+ rcall i2c_write
+ ldi temp2,3
+ rcall i2c_read ;get year (stored in RTC-RAM addr. 10h)
+ tst temp
+ breq rtc_get_e
+
+ ldd temp3,z+1 ;save year
+ ldd temp4,z+2
+
+ ldi temp2,2 ;register pointer. 2 = secs
+ std z+1,temp2
+ rcall i2c_write
+ ldi temp2,6
+ rcall i2c_read
+ tst temp
+ breq rtc_get_e
+
+ ldd temp,z+4 ;get year
+ rol temp
+ rol temp
+ rol temp
+ eor temp,temp3
+ andi temp,0x03
+ breq rtc_get_1
+ inc temp3
+ adc temp4,_0
+rtc_get_1:
+ ldiw x,clock
+ cli
+
+ ldd temp,z+1 ;get seconds
+ rcall bcdbin2
+ st x+,temp
+ ldd temp,z+2 ;get minutes
+ rcall bcdbin2
+ st x+,temp
+ ldd temp,z+3 ;get hours
+ rcall bcdbin2
+ st x+,temp
+ ldd temp,z+4 ;get day
+ andi temp,0x3f
+ rcall bcdbin2
+ st x+,temp
+ ldd temp,z+5 ;get months
+ andi temp,0x1f
+ rcall bcdbin2
+ st x+,temp ;store month
+ st x+,temp3 ;store year
+ st x+,temp4 ;store year century
+ sei
+
+rtc_get_e:
+ pop temp
+ pop temp
+ pop temp
+ pop temp
+ pop temp
+ pop temp
+ ret
+
+;----------------------------------------------
+; Set hardware clock from software clock
+;
+; Register: temp2: s
+; temp3: m
+; temp4: h
+; xl: D
+; temp: M
+; yl: Yl
+; yh: Yh
+
+rtc_set:
+ ldiw z,clock
+ cli
+ ldd temp2,z+0 ;sec
+ ldd temp3,z+1 ;min
+ ldd temp4,z+2 ;hours
+ ldd xl,z+3 ;day
+ ldd temp,z+4 ;month
+ ldd yl,z+5 ;yearl
+ ldd yh,z+6 ;yearh
+ sei
+ rcall binbcd2
+ push temp ;-1 save month
+ mov temp,xl
+ rcall binbcd2
+ mov xl,yl ; least significant 2 bits of year
+ swap xl
+ lsl xl
+ lsl xl
+ andi xl,0xc0
+ or temp,xl ; combine with day
+ push temp ;-2 save year/day
+ mov temp,temp4
+ rcall binbcd2
+ push temp ;-3 save hours
+ mov temp,temp3
+ rcall binbcd2
+ push temp ;-4 save min
+ mov temp,temp2
+ rcall binbcd2
+ push temp ;-5 save sec
+
+ push _0 ;-6 1/10s, 1/100s
+ ldi temp,0x84 ; stop count, alarm enable
+ push temp ;-7
+ push _0 ;-8 register address
+ in zh,sph
+ in zl,spl
+ ldi temp,0xA0 ; PCF8583 slave address
+ push temp ;(-9)
+
+ ldi temp2,9
+ rcall i2c_write
+ ldi temp,0x04 ;enable counting
+ std z+2,temp
+ ldi temp2,3
+ rcall i2c_write
+ std z+3,yh ;store year in RTC RAM
+ std z+2,yl
+ ldi temp,0x10
+ std z+1,temp
+ ldi temp2,4
+ rcall i2c_write
+
+ addiw z,8 ;remove buffer from stack
+ cli
+ out spl,zl
+ sei
+ out sph,zh
+
+ ret
+#endif
+