# Metronome and beat maker: a free micro:bit lesson from Maze Education
# https://maze.education/microbit/lessons/metronome
# MicroPython for the micro:bit Python Editor: https://python.microbit.org

# Metronome: the logo starts and stops the beat, A slows it and B speeds it up; beat 1 of 4 is higher (micro:bit V2).
from microbit import *
import music

bpm = 90
playing = False
beat = 0

while True:
    if button_a.was_pressed():
        bpm = max(bpm - 10, 40)
        display.scroll(str(bpm))
    if button_b.was_pressed():
        bpm = min(bpm + 10, 200)
        display.scroll(str(bpm))
    if pin_logo.is_touched():
        playing = not playing
        while pin_logo.is_touched():
            sleep(20)
    if playing:
        beat = beat + 1
        if beat > 4:
            beat = 1
        if beat == 1:
            music.pitch(988, 40)
        else:
            music.pitch(659, 40)
        display.set_pixel(beat - 1, 2, 9)
        sleep(60)
        display.clear()
        sleep(60000 // bpm - 100)
    else:
        sleep(50)
