Skip to content

Instantly share code, notes, and snippets.

@cwyark
Last active March 27, 2017 12:59
Show Gist options
  • Save cwyark/5f75a9179bdb0d2bcca5d695095c6842 to your computer and use it in GitHub Desktop.
Save cwyark/5f75a9179bdb0d2bcca5d695095c6842 to your computer and use it in GitHub Desktop.
ds1338 driver for micropython
import utime as time
import umachine as machine
import ubinascii as binascii
ds1338_address = 0b1101000
def _bcd_to_int(bcd):
out = 0
for d in (bcd >> 4, bcd):
for p in (1, 2, 4 ,8):
if d & 1:
out += p
d >>= 1
out *= 10
return out // 10
def _int_to_bcd(n):
bcd = 0
for i in (n // 10, n % 10):
for p in (8, 4, 2, 1):
if i >= p:
bcd += 1
i -= p
bcd <<= 1
return bcd >> 1
class DS1338Drv:
def __init__(self, i2c):
if type(i2c) is not machine.I2C:
raise ValueError("Not a valid I2C type")
self.i2c = i2c
self.reg_map = bytearray(8)
def getRegMap(self):
return self.i2c.mem_read(self.reg_map, ds1338_address, 0x00)
def getCurrentTime(self):
ret = self.getRegMap()
second = _bcd_to_int(ret[0])
minute = _bcd_to_int(ret[1])
hour = _bcd_to_int(ret[2])
day = _bcd_to_int(ret[3])
date = _bcd_to_int(ret[4])
month = _bcd_to_int(ret[5])
year = 2000 + _bcd_to_int(ret[6])
return (second, minute, hour, day, date, month, year)
def setCurrentTime(self, datetime):
second = _int_to_bcd(datetime[0])
minute = _int_to_bcd(datetime[1])
hour = _int_to_bcd(datetime[2])
day = _int_to_bcd(datetime[3])
date = _int_to_bcd(datetime[4])
month = _int_to_bcd(datetime[5])
year = _bcd_to_int(datetime[6] - 2000)
l = [second, minute, hour, day, date, month, year]
b = bytearray(l)
self.i2c.mem_write(b, ds1338_address, 0x00)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment