from machine import I2C, Pin, PWM
import utime
class DS1307:
def __init__(self, i2c):
self.i2c = i2c
self.address = 0x68
def _bcd_to_dec(self, bcd):
return (bcd // 16) * 10 + (bcd % 16)
def _dec_to_bcd(self, dec):
return (dec // 10) * 16 + (dec % 10)
def get_time(self):
try:
data = self.i2c.readfrom_mem(self.address, 0x00, 7)
seconds = self._bcd_to_dec(data[0])
minutes = self._bcd_to_dec(data[1])
hours = self._bcd_to_dec(data[2])
day = self._bcd_to_dec(data[3])
date = self._bcd_to_dec(data[4])
month = self._bcd_to_dec(data[5])
year = self._bcd_to_dec(data[6]) + 2000
return (year, month, date, hours, minutes, seconds)
except OSError as e:
print(f"Error reading from DS1307: {e}")
return None
def set_time(self, year, month, date, day, hours, minutes, seconds):
self.i2c.writeto_mem(self.address, 0x00, bytearray([
self._dec_to_bcd(seconds),
self._dec_to_bcd(minutes),
self._dec_to_bcd(hours),
self._dec_to_bcd(day),
self._dec_to_bcd(date),
self._dec_to_bcd(month),
self._dec_to_bcd(year - 2000)
]))
# Initialize I2C
i2c = I2C(0, scl=Pin(1), sda=Pin(0))
# Initialize DS1307
rtc = DS1307(i2c)
# Initialize Servo Motor
servo_pin = Pin(15)
pwm = PWM(servo_pin)
pwm.freq(50) # Standard frequency for servos
def set_servo_angle(angle):
# Convert the angle to a duty cycle (0-1023 for 10-bit resolution)
duty = int(500 + (angle / 180) * 2000)
pwm.duty_u16(duty * 65535 // 1023)
while True:
time_data = rtc.get_time()
if time_data:
year, month, date, hours, minutes, seconds = time_data
print(f"{hours}:{minutes}:{seconds} {date}/{month}/{year}")
# Check if the current time is 15:36
if hours == 15 and minutes == 36:
set_servo_angle(90) # Example angle to move the servo to
print("Servo moved to 90 degrees at 15:36")
utime.sleep(1)