Python code: Exploring songs

import math
import time

from adafruit_circuitplayground import cp

# These are the frequencies of the three notes.
note1 = 261.63
note2 = 293.66
note3 = 329.63

# If the balance board tilts beyond "tilt" degrees, different notes will be played.
tilt = 7

# Time (in seconds) to keep a horizontal position before note2 is played.
# This allows to switch from note1 to note3 (or vice versa) without playing note2.
horizontal = 0.7

# Initialise note, now and sound.
note = 0
now = time.monotonic()
sound = False

# Loop forever
while True:
    if cp.button_a:
        sound = True
    elif cp.button_b:
        cp.stop_tone()
        cp.pixels.fill((0, 0, 0))
        sound = False

    if not sound:
        continue

    # Initialise a_x, a_y, and a_z.
    a_x = 0
    a_y = 0
    a_z = 0

    # Take 10 measurements for a_x, a_y, and a_z.
    for count in range(10):
        x, y, z = cp.acceleration
        a_x = a_x + x
        a_y = a_y + y
        a_z = a_z + z
        time.sleep(0.02)

    # Calculate the average of the 10 measurements.
    a_x = a_x / 10
    a_y = a_y / 10
    a_z = a_z / 10

    # Compute acceleration using norm.
    acceleration = math.sqrt(a_x*a_x + a_y*a_y + a_z*a_z)

    # Compute 𝛼 (atan returns radians), convert it to degrees,
    # then convert it to an integer.
    alpha = int(math.degrees(math.atan(a_x / a_z)))

    # The board's tilt determines the note played and the color of the NeoPixels.
    if alpha > tilt:
        if note != 3:
            note = 3
            cp.stop_tone()
            cp.pixels.fill((220, 20, 60))
            cp.start_tone(note3)
        now = time.monotonic()
    elif alpha < -tilt:
        if note != 1:
            note = 1
            cp.stop_tone()
            cp.pixels.fill((0, 128, 0))
            cp.start_tone(note1)
        now = time.monotonic()
    else:
        if note != 2:
            note = 2
            cp.stop_tone()
        if (now + horizontal) > time.monotonic():
            cp.pixels.fill((255, 99, 71))
            cp.start_tone(note2)