rtc udpate
This commit is contained in:
31
RTC/read.py
31
RTC/read.py
@@ -20,20 +20,29 @@ def bcd_to_dec(bcd):
|
|||||||
return (bcd // 16 * 10) + (bcd % 16)
|
return (bcd // 16 * 10) + (bcd % 16)
|
||||||
|
|
||||||
def read_time(bus):
|
def read_time(bus):
|
||||||
data = bus.read_i2c_block_data(DS3231_ADDR, REG_TIME, 7)
|
"""Try to read and decode time from the RTC module (DS3231)."""
|
||||||
seconds = bcd_to_dec(data[0] & 0x7F)
|
try:
|
||||||
minutes = bcd_to_dec(data[1])
|
data = bus.read_i2c_block_data(DS3231_ADDR, REG_TIME, 7)
|
||||||
hours = bcd_to_dec(data[2] & 0x3F)
|
seconds = bcd_to_dec(data[0] & 0x7F)
|
||||||
day = bcd_to_dec(data[4])
|
minutes = bcd_to_dec(data[1])
|
||||||
month = bcd_to_dec(data[5])
|
hours = bcd_to_dec(data[2] & 0x3F)
|
||||||
year = bcd_to_dec(data[6]) + 2000
|
day = bcd_to_dec(data[4])
|
||||||
return (year, month, day, hours, minutes, seconds)
|
month = bcd_to_dec(data[5])
|
||||||
|
year = bcd_to_dec(data[6]) + 2000
|
||||||
|
return datetime(year, month, day, hours, minutes, seconds)
|
||||||
|
except OSError:
|
||||||
|
return None # RTC module not connected
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
# Read RTC time
|
# Read RTC time
|
||||||
bus = smbus2.SMBus(1)
|
bus = smbus2.SMBus(1)
|
||||||
year, month, day, hours, minutes, seconds = read_time(bus)
|
# Try to read RTC time
|
||||||
rtc_time = datetime(year, month, day, hours, minutes, seconds)
|
rtc_time = read_time(bus)
|
||||||
|
# If RTC is not connected, set default message
|
||||||
|
if rtc_time is None:
|
||||||
|
rtc_time_str = "not connected"
|
||||||
|
else:
|
||||||
|
rtc_time_str = rtc_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
|
||||||
# Get current system time
|
# Get current system time
|
||||||
system_time = datetime.now() #local
|
system_time = datetime.now() #local
|
||||||
@@ -46,7 +55,7 @@ def main():
|
|||||||
|
|
||||||
# Create JSON output
|
# Create JSON output
|
||||||
time_data = {
|
time_data = {
|
||||||
"rtc_module_time": rtc_time.strftime('%Y-%m-%d %H:%M:%S'),
|
"rtc_module_time":rtc_time_str,
|
||||||
"system_local_time": system_time.strftime('%Y-%m-%d %H:%M:%S'),
|
"system_local_time": system_time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||||
"system_utc_time": utc_time.strftime('%Y-%m-%d %H:%M:%S')
|
"system_utc_time": utc_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user