# SPDX-FileCopyrightText: Copyright (c) 2024 Cooper Dalrymple
#
# SPDX-License-Identifier: Unlicense

import board
import ulab.numpy as np

import pio_i2s

# The update rate per second which will determine the size of our audio buffer
RATE = 10

mic = pio_i2s.I2S(
    bit_clock=board.GP0,  # word select is GP1
    data_in=board.GP2,
    channel_count=1,
    sample_rate=48000,
    bits_per_sample=16,  # ulab.numpy only works with integers up to 16-bits
    samples_signed=True,
)

# Create an array which will contain one second of audio data
data = np.array([0] * int(mic.sample_rate * mic.channel_count / RATE), dtype=np.int16)

while True:
    
    # Record one second of audio samples from the microphone into our array
    mic.record(data)
    
    # Determine the level of the incoming audio using ulab.numpy
    level = (np.max(data) - np.min(data)) / 65536  # should contain a value from 0.0 to 1.0
    print(level * 100)  # scale to 0.0 to 100.0