# GN2R Starship Control Code for ESP32 (MicroPython) - Fixed & Enhanced!
from machine import Pin, PWM
import time
import random
# --- Setup Pins ---
buzzer_pin = Pin(15, Pin.OUT)
led1 = Pin(23, Pin.OUT)
led2 = Pin(22, Pin.OUT)
led3 = Pin(32, Pin.OUT)
all_leds = [led1, led2, led3]
buzzer = PWM(buzzer_pin)
# --- Note Frequencies ---
NOTE_FREQS = {
'C4': 262, 'D4': 294, 'E4': 330, 'F4': 349, 'G4': 392, 'A4': 440, 'B4': 494,
'C5': 523, 'D5': 587, 'E5': 659, 'F5': 698, 'G5': 784, 'A5': 880, 'B5': 988,
'REST': 0
}
# --- Jingle Bells Melody (FIXED!) ---
jingle_bells_melody = [
('E5', 0.5), ('E5', 0.5), ('E5', 1),
('E5', 0.5), ('E5', 0.5), ('E5', 1),
('E5', 0.5), ('G5', 0.5), ('C5', 0.5), ('D5', 0.5), ('E5', 1.5),
('REST', 0.5),
('F5', 0.5), ('F5', 0.5), ('F5', 0.5), ('F5', 0.5),
('F5', 0.5), ('E5', 0.5), ('E5', 0.5), ('E5', 0.5),
('E5', 0.5), ('D5', 0.5), ('D5', 0.5), ('E5', 0.5), ('D5', 1), ('G5', 1)
]
# --- Tempo ---
BPM = 120
beat_duration = 60 / BPM
# --- Play Note with Independent LED Dance ---
def play_note_with_leds(note, duration_beats):
actual_duration = duration_beats * beat_duration
start_time = time.ticks_ms()
end_time = start_time + int(actual_duration * 1000 * 0.8)
if note == 'REST':
buzzer.duty(0)
for led in all_leds:
led.value(0)
time.sleep(actual_duration)
return
buzzer.freq(NOTE_FREQS[note])
buzzer.duty(512)
blink_interval = 100
next_blink = start_time
while time.ticks_ms() < end_time:
if time.ticks_ms() >= next_blink:
for led in all_leds:
led.value(0)
random.choice(all_leds).value(1)
next_blink += blink_interval
time.sleep_ms(10)
buzzer.duty(0)
for led in all_leds:
led.value(0)
time.sleep(actual_duration * 0.2)
# --- Main ---
print("GN2R: Initiating Jingle Bells with LED Dance!")
buzzer.init(freq=1000, duty=0)
try:
while True:
for note, duration in jingle_bells_melody:
play_note_with_leds(note, duration)
time.sleep(2)
except KeyboardInterrupt:
print("GN2R: Sequence stopped.")
buzzer.duty(0)
for led in all_leds:
led.value(0)
buzzer.deinit()