# mPy - FKS0001 audio excercises with i2s, predefined wave
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-01-25  initial release

from	machine	import	Pin, I2S, freq;		freq(240_000_000)
import	math
import	struct

# =========================== local ============================

# I2S protocol requires 3 wires i.e.:
#    SCK (Serial clock)  BCK	pin 14
#    WS  (Word clock  )  LCK	pin 26
#    SD  (Serial data )  DIN	pin 27

# Return 1 sinus of freq made with samplerate rate, volume 0.0 .. 1.0
def makeSinus(freq, volume, rate=44100):
    n_samples = rate // freq                    # for 1 sinus
    buffer    = bytearray(n_samples * 2)		# 16 bits per sample
    amplitude = int(32767 * volume)
    for i in range(n_samples):
        y = amplitude + int(amplitude * math.sin(2 * math.pi * i / n_samples))
        struct.pack_into("<h", buffer, i * 2, y)
    return buffer

# ============================ main =============================

# on FKS0001: sck=BCK, ws=LCK and sd=DIN
def main():
    i2s = I2S(1, sck=Pin(14), ws=Pin(26), sd=Pin(27), mode=I2S.TX,
              bits=16, format=I2S.MONO, rate=44100, ibuf=20000)
    samples = makeSinus(freq=1000, volume=0.2)
    try:
        while True:
            i2s.write(samples)			# blocking write
    finally:
        i2s.deinit()
        print("Done")


main()

# ============================= end ===============================
