# GN2R Starship Control Code for ESP32 (MicroPython)
from machine import Pin, PWM
import time
# --- Setup Pins ---
# Connect your LEDs' positive (long) legs to current-limiting resistors (e.g., 220 Ohm),
# then to GPIOs 23, 22, and 32. The negative (short) legs go to GND.
# Connect your buzzer's positive leg to GPIO 15 and negative leg to GND.
buzzer_pin = Pin(15, Pin.OUT) # GPIO for the buzzer
led1 = Pin(23, Pin.OUT) # GPIO for LED 1 (Moved from input-only pin 34)
led2 = Pin(22, Pin.OUT) # GPIO for LED 2 (Moved from input-only pin 35)
led3 = Pin(32, Pin.OUT) # GPIO for LED 3
# Group LEDs for easy control
all_leds = [led1, led2, led3]
# Initialize buzzer using PWM
buzzer = PWM(buzzer_pin)
# --- Musical Note Frequencies (Hz) ---
# These are standard frequencies for musical notes
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 # Use 0 frequency for a pause (no sound)
}
# --- Jingle Bells Melody ---
# Each item is a tuple: (Note, Duration in beats)
# This is a simplified version of Jingle Bells
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), # Oh! what fun it is to ride
('REST', 0.5), # Small pause
('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) # Jingle all the way
]
# --- Tempo ---
# Adjust this value to make the song faster or slower
BPM = 120 # Beats Per Minute
beat_duration = 60 / BPM # Duration of one beat in seconds
# --- Function to Play a Note with LEDs ---
def play_note_with_leds(note, duration_beats):
actual_duration = duration_beats * beat_duration
if note == 'REST':
buzzer.duty(0) # Turn buzzer off
for led in all_leds:
led.value(0) # Turn all LEDs off
else:
buzzer.freq(NOTE_FREQS[note]) # Set buzzer frequency
buzzer.duty(512) # Set 50% duty cycle (turns buzzer on)
for led in all_leds:
led.value(1) # Turn all LEDs on
time.sleep(actual_duration * 0.8) # Play note for 80% of its duration
buzzer.duty(0) # Turn buzzer off
for led in all_leds:
led.value(0) # Turn all LEDs off
time.sleep(actual_duration * 0.2) # Small pause for note separation
# --- Main Program ---
print("GN2R: Initiating Jingle Bells sequence with LEDs!")
buzzer.init(freq=1000, duty=0) # Initialize buzzer PWM (off)
try:
while True: # Loop the song forever
for note, duration in jingle_bells_melody:
play_note_with_leds(note, duration)
time.sleep(2) # Pause between song repeats
except KeyboardInterrupt:
print("GN2R: Jingle Bells sequence interrupted!")
buzzer.duty(0) # Ensure buzzer is off
for led in all_leds:
led.value(0) # Ensure all LEDs are off
buzzer.deinit() # De-initialize PWM for buzzer