# Демьяненко Вячеслав К0709-22/2 & Литвинов Егор
from machine import Pin, I2C
from ds1307 import DS1307
from utime import sleep
from random import randint
import rp2

@rp2.asm_pio(out_init=[rp2.PIO.OUT_LOW])
def echo():
    wrap_target()
    mov(pins, isr)     
    mov(isr, invert(isr))
    pull(noblock)      
    mov(x, osr)
    mov(y, x)
    label("loop")
    jmp(y_dec, "loop")  
    wrap()

sm = rp2.StateMachine(0, echo, freq=1_000_000, out_base=Pin(20))
sm.active(1)

led = Pin(28, Pin.OUT)

SUNDAY = 8
SATURDAY = 7

DEFAULT_I2C_ADDR = 0x27

i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=10000000)
ds1307 = DS1307(addr=0x68, i2c=i2c)

btn = Pin(26, Pin.IN)
relay = Pin(28, Pin.OUT)
sm.put(0)

timer_wait = randint(5, 15)
timer = ds1307.minute
pil_wait = 3


def check_morning():
    return 7 * 60 <= ds1307.hour * 60 + ds1307.minute <= 8 * 60 + 20

def check_evening():
    return 20 * 60 <= ds1307.hour * 60 + ds1307.minute <= 21 * 60

def play(freq):
  if freq:
    sm.put(1_000_000//freq)
  else:
    sm.put(0)

while True:
    if ds1307.weekday in {SUNDAY, SATURDAY}:
        continue

    if not(check_morning() or check_evening()):
        continue

    if ds1307.minute == timer + timer_wait:
        cur_time = ds1307.minute
        while cur_time + pil_wait != ds1307.minute:
            if btn.value():
                led.off()
                play()
                break
            play(500)
            led.on()
            sleep(0.5)
        else:
            play()
            led.off()
            pil_wait += 1
        timer = ds1307.minute
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
GND5VSDASCLSQWRTCDS1307+