# mPy - FKS0001 audio exercises with i2s, 200 - 2000 Hz sweep
# 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 sweep pattern in buffer (mono, 16 bit, 44k1 kHz)
def makeSweep():
    n_samples = 44100                     		# for 1 seconds
    buffer    = bytearray(n_samples * 2)		# 16 bits per sample
    amplitude = 32767
    dt_start  = ( 200 / 44100) * 2 * math.pi
    dt_end    = (2000 / 44100) * 2 * math.pi
    t         = 0
    for i in range(n_samples):
        dt = dt_start + (dt_end - dt_start) * i / n_samples
        t += dt
        y = amplitude + int(amplitude * math.sin(t))
        struct.pack_into("<h", buffer, i * 2, y)
        if not i % 1000: print('*', end='')
    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=2000)
    samples = makeSweep()
    try:
        while True:
            i2s.write(samples)			# blocking write
    finally:
        i2s.deinit()
        print("Done")


main()

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