# How loud is our classroom? A sound graph: a free micro:bit lesson from Maze Education
# https://maze.education/microbit/lessons/sound-graph
# MicroPython for the micro:bit Python Editor: https://python.microbit.org

# How loud is our classroom? A starts logging the average and loudest sound every ten seconds, B stops (micro:bit V2).
from microbit import *
import log

log.set_labels("average", "loudest", timestamp=log.SECONDS)
logging = False
total = 0
samples = 0
loudest = 0


@run_every(s=10)
def record():
    global total, samples, loudest
    if logging and samples > 0:
        log.add({"average": total // samples, "loudest": loudest})
        total = 0
        samples = 0
        loudest = 0


while True:
    if button_a.was_pressed():
        logging = True
        display.show(Image.YES)
    if button_b.was_pressed():
        logging = False
        display.show(Image.NO)
    if logging:
        level = microphone.sound_level()
        total = total + level
        samples = samples + 1
        if level > loudest:
            loudest = level
    sleep(100)
