from machine import Pin, PWM
import time
import random
# Constants
NOTE_FREQ = {
'A': 440.00, 'A#': 466.16, 'Bb': 466.16,
'B': 493.88, 'C': 523.25,
'C#': 554.37, 'Db': 554.37,
'D': 587.33, 'D#': 622.25, 'Eb': 622.25,
'E': 659.25, 'F': 698.46,
'F#': 739.99, 'Gb': 739.99,
'G': 783.99, 'G#': 830.61, 'Ab': 830.61
}
SCALES = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
SCALE_NOTES = {
'A': ['A', 'B', 'C#', 'D', 'E', 'F#', 'G#'],
'B': ['B', 'C#', 'D#', 'E', 'F#', 'G#', 'A#'],
'C': ['C', 'D', 'E', 'F', 'G', 'A', 'B'],
'D': ['D', 'E', 'F#', 'G', 'A', 'B', 'C#'],
'E': ['E', 'F#', 'G#', 'A', 'B', 'C#', 'D#'],
'F': ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'],
'G': ['G', 'A', 'B', 'C', 'D', 'E', 'F#']
}
# Initialize hardware
buzzer = PWM(Pin(10)) # Change pin number as needed
# Function to play a note
def play_note(note, duration=0.5):
freq = NOTE_FREQ.get(note, 440) # Default to 440Hz if note not found
buzzer.freq(int(freq))
buzzer.duty_u16(32768) # Set to mid-level duty cycle for sound
time.sleep(duration)
buzzer.duty_u16(0) # Turn off sound
# Function to play a scale
def play_scale(scale):
notes = SCALE_NOTES[scale]
for note in notes:
play_note(note, 0.5)
time.sleep(0.1)
# Function to get user input
def get_user_input():
# Replace this with actual button reading code
return input("Enter your guess (A-G): ").upper()
# Function to display the score via serial output
def display_score(score):
print(f"Score: {score}")
# Main game loop
def main():
score = 0 # Initialize score
while True:
# Display scale options and get user choice
print("Select a scale: A, B, C, D, E, F, G")
scale = input().upper()
if scale not in SCALES:
print("Invalid scale")
continue
# Play the chosen scale
play_scale(scale)
# Wait for 2 seconds
time.sleep(2)
# Initialize the list of notes to guess
notes = SCALE_NOTES[scale]
notes_to_guess = []
while True:
# Add a new note to the notes_to_guess list
if len(notes_to_guess) < len(notes):
new_note = random.choice(notes)
notes_to_guess.append(new_note)
# Play the sequence of notes
for note in notes_to_guess:
play_note(note)
time.sleep(2)
# Get user guesses
user_guesses = [get_user_input() for _ in range(len(notes_to_guess))]
# Check if all guesses are correct
if user_guesses == notes_to_guess:
print("Correct!")
score += 1 # Increment score for correct guesses
display_score(score)
play_scale(scale)
time.sleep(2)
else:
print("Wrong! Try again.")
notes_to_guess = []
play_scale(scale)
time.sleep(2)
# Optionally, you can break out of the outer loop to end the game
# For example:
# break
if __name__ == "__main__":
main()