Skip to content

Instantly share code, notes, and snippets.

@yuliantoeric
Last active November 23, 2022 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuliantoeric/10ab837589ffab52feca87e62e61efe0 to your computer and use it in GitHub Desktop.
Save yuliantoeric/10ab837589ffab52feca87e62e61efe0 to your computer and use it in GitHub Desktop.
Microbit-Micropython snippet for DS1307 real-time clock
from microbit import i2c
RTC_ADDR = 0x68
def bcd2bin(v):
return v - 6 * (v >> 4)
def bin2bcd(v):
return v + 6 * (v // 10)
def rtc_gettime():
i2c.write(RTC_ADDR, b'\x00')
value = i2c.read(RTC_ADDR, 7)
ss = bcd2bin(value[0] & 0x7F)
mm = bcd2bin(value[1])
hh = bcd2bin(value[2])
d = bcd2bin(value[4])
m = bcd2bin(value[5])
y = bcd2bin(value[6]) + 2000
return [y, m, d, hh, mm, ss]
def rtc_settime(y, m, d, hh, mm, ss):
value = []
value.append(bin2bcd(ss))
value.append(bin2bcd(mm))
value.append(bin2bcd(hh))
value.append(bin2bcd(0))
value.append(bin2bcd(d))
value.append(bin2bcd(m))
value.append(bin2bcd(y - 2000))
i2c.write(RTC_ADDR, b'\x00' + bytearray(value))
# rtc_gettime()
# rtc_settime(2017, 5, 22, 14, 23, 0)
# rtc_gettime() -> [2017, 5, 22, 14, 23, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment