from machine import Pin, SoftI2C
import ssd1306
import time
class DS1307:
def __init__(self, i2c):
self.i2c = i2c
self.addr = 0x68 # Dirección I2C del DS1307
def _bcd2dec(self, bcd):
return (bcd // 16) * 10 + (bcd % 16)
def _dec2bcd(self, dec):
return (dec // 10) * 16 + (dec % 10)
def datetime(self, dt=None):
if dt is None:
# Leer la hora y fecha del DS1307
data = self.i2c.readfrom_mem(self.addr, 0x00, 7)
seconds = self._bcd2dec(data[0] & 0x7F)
minutes = self._bcd2dec(data[1])
hours = self._bcd2dec(data[2] & 0x3F)
day = self._bcd2dec(data[4])
month = self._bcd2dec(data[5] & 0x1F)
year = self._bcd2dec(data[6]) + 2000
return (year, month, day, hours, minutes, seconds)
else:
# Establecer la hora y fecha
year, month, day, hours, minutes, seconds = dt
data = bytearray(7)
data[0] = self._dec2bcd(seconds)
data[1] = self._dec2bcd(minutes)
data[2] = self._dec2bcd(hours)
data[4] = self._dec2bcd(day)
data[5] = self._dec2bcd(month)
data[6] = self._dec2bcd(year - 2000)
self.i2c.writeto_mem(self.addr, 0x00, data)
# Configuración del I2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
# Inicializar la pantalla OLED
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Inicializar el RTC DS1307
rtc = DS1307(i2c)
# Ajuste de hora para UTC -6
def ajustar_hora_mexico(hora_utc):
year, month, day, hours, minutes, seconds = hora_utc
# Ajuste para UTC -6
if hours < 0:
hours += 24
day -= 1
# Ajuste de fecha para el cambio de mes
if day <= 0:
month -= 1
day = 31 # Simplificado: ajustar según el mes anterior
# Asegúrate de no tener valores incorrectos en el mes o día
if month <= 0:
month += 12
year -= 1
if day > 31: # Ajustar para meses con menos de 31 días
day = 31
return (year, month, day, hours, minutes, seconds)
# Bucle principal para mostrar la hora
while True:
# Obtener la hora UTC del RTC
hora_utc = rtc.datetime()
# Ajustar la hora para México
hora_mexico = ajustar_hora_mexico(hora_utc)
# Mostrar la hora en la pantalla OLED
year, month, day, hours, minutes, seconds = hora_mexico
oled.fill(0) # Limpiar la pantalla
# Mostrar la fecha
oled.text('Fecha: {:02d}/{:02d}/{:04d}'.format(day, month, year), 0, 0)
# Mostrar la hora en formato HH:MM:SS
oled.text('Hora: {:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds), 0, 16)
oled.show()
time.sleep(1) # Actualizar cada segundo