from machine import Pin, SoftI2C
import ssd1306
import machine
import time
import _thread

# Set up the GPIO pin connected to the piezo buzzer
buzzer_pin = machine.Pin(13, machine.Pin.OUT)

# Define notes frequencies (in Hertz)
# Format: (note, duration)
notes = [
    (440, 500),   # A
    (440, 500),   # A
    (440, 500),   # A
    (349, 350),   # F
    (523, 150),   # C
    (440, 500),   # A
    (349, 350),   # F
    (523, 150),   # C
    (440, 1000),  # A
    (659, 500),   # E
    (659, 500),   # E
    (659, 500),   # E
    (698, 350),   # F#
    (523, 150),   # C
    (415, 500),   # Ab
    (349, 350),   # F
    (523, 150),   # C
    (440, 1000),  # A
]


# Function to play a note
def play_note(pin, freq, dur):
    pwm = machine.PWM(pin)
    pwm.freq(freq)
    pwm.duty(512)  # 50% duty cycle
    time.sleep(dur / 1000)  # Convert duration to seconds
    pwm.deinit()    # Turn off the PWM
    time.sleep(0.05)  # Add a small delay between notes

# Function to play a note
def play_note_thread(freq, dur):
    play_note(buzzer_pin, freq, dur)

# Create a thread for music playback
def play_music_thread():
    for note_freq, note_dur in notes:
        play_note_thread(note_freq, note_dur)

# Text to scroll
star_wars_text = [
    "A long time ago,",
    "in a galaxy far,",
    "far away...",
    "",
    "STAR WARS",
    "",
    "Episode IV",
    "A NEW HOPE",
    "",
    "It is a period",
    "of civil war. Rebel",
    "spaceships, striking",
    "from a hidden base, ",
    "have won their first",
    "victory against the",
    "evil Galactic Empire.",
    "",
    "During the battle,",
    "Rebel spies managed",
    "to steal secret",
    "plans to the",
    "Empire's ultimate weapon",
    "the DEATH STAR",
    "an armored space station",
    "with enough power to",
    "destroy an entire planet.",
    "",
    "Pursued by the Empire’s",
    "sinister agents, Princess",
    "Leia races home aboard her",
    "starship, custodian of the",
    "stolen plans that can save",
    "her people and restore",
    "freedom to the galaxy..."
]

# ESP32 Pin assignment 
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

# Initial position
y_position = oled_height

# Start the music playback thread
_thread.start_new_thread(play_music_thread, ())

while True:
    # Clear display
    oled.fill(0)

    # Draw each line of the text
    for i, line in enumerate(star_wars_text):
        y = y_position + (i * 10)
        oled.text(line, 0, y)
    
    # Display the frame
    oled.show()

    # Move the text up by 1 pixel
    y_position -= 1

    # When the last line of the text goes out of the display,
    # reset y_position to start over
    if y_position + len(star_wars_text) * 10 < 0:
        y_position = oled_height

    # Delay to control the speed of the scrolling
    time.sleep(0.1)