"""Module 10: play a repeating melody on the passive buzzer at GP21."""

import time
import board
import pwmio
import busio
import adafruit_ssd1306


def show_module(oled, number, title, lines):
    """Draw this lesson's OLED screen without an external helper module."""
    oled.fill(0)
    oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
    for index, line in enumerate(lines[:4]):
        oled.text(str(line)[:21], 0, 16 + index * 11, 1)
    oled.show()


MELODY = (
    (2637, 0.15), (2637, 0.15), (0, 0.15), (2637, 0.15),
    (0, 0.15), (2093, 0.15), (2637, 0.15), (0, 0.15),
    (3136, 0.30), (0, 0.30), (1568, 0.30), (0, 0.30),
)

i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
buzzer = pwmio.PWMOut(
    board.GP21,
    frequency=440,
    duty_cycle=0,
    variable_frequency=True,
)
show_module(oled, 10, "Audio & Buzzer", (
    "Buzzer: GP21",
    "Audio output: GP20",
    "Playing melody",
))

try:
    while True:
        for frequency, duration in MELODY:
            if frequency:
                buzzer.frequency = frequency
                buzzer.duty_cycle = 32768
            else:
                buzzer.duty_cycle = 0
            time.sleep(duration)
        buzzer.duty_cycle = 0
        time.sleep(0.5)
finally:
    buzzer.duty_cycle = 0
    buzzer.deinit()
    i2c.deinit()
