import utime, uctypes
from machine import Pin
import rp2
from dma import DMA

@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW, autopush=True, sideset_init=(rp2.PIO.OUT_HIGH, rp2.PIO.OUT_HIGH, rp2.PIO.OUT_HIGH))
def mcp3202():
    nop()           .side(0b111)
    wait(1,pin, 1)  .side(0b111)    # CS, CLK, Din

    nop()           .side(0b001)    # Start bit
    in_(null, 1)    .side(0b011)
    in_(null, 1)    .side(0b001)    # SGL bit
    in_(null, 1)    .side(0b011)
    nop()           .side(0b000)    # L/R bit
    nop()           .side(0b010)
    nop()           .side(0b001)    # MSBF bit
    nop()           .side(0b011)
    set(x, 12)           .side(0b001)    # null bit
    label("data_loop0")
    in_(pins, 1)    .side(0b011)
    jmp(x_dec, "data_loop0") .side(0b001)

    nop()   .side(0b111)
    wait(0,pin, 1)  .side(0b111)

    nop()           .side(0b001)    # Start bit
    in_(null, 1)    .side(0b011)
    in_(null, 1)    .side(0b001)    # SGL bit
    in_(null, 1)    .side(0b011)
    nop()           .side(0b001)    # L/R bit
    nop()           .side(0b011)
    nop()           .side(0b001)    # MSBF bit
    nop()           .side(0b011)
    set(x, 12)           .side(0b001)    # null bit
    label("data_loop1")
    in_(pins, 1)    .side(0b011)
    jmp(x_dec, "data_loop1") .side(0b001)

@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW)
def osc():
    nop()   .side(0)
    nop()   .side(1)


DMA.abort_all()

PIO0_BASE      = 0x50200000
PIO0_BASE_RXF1 = PIO0_BASE + 0x24

buf = bytearray(4000)
dma = DMA(0)
dma.config( 
    read_addr = PIO0_BASE_RXF1, 
    write_addr = uctypes.addressof( buf ),
    trans_count = len( buf ) // 4, 
    read_inc = False, 
    write_inc = True, 
    data_size = DMA.SIZE_WORD,
    treq_sel = DMA.DREQ_PIO0_RX1
)

dma.enable()

Pin(3,Pin.IN)
sm = rp2.StateMachine(1, mcp3202, freq=1800000, sideset_base=Pin(4), in_base = Pin(2,Pin.IN))
sm.active(1)

osm = rp2.StateMachine(0, osc, freq=20000, sideset_base=Pin(1))
osm.active(1)

utime.sleep(1)

print(buf[0:15])

#lr = Pin(1, Pin.OUT)
while(True):
    pass
#    lr.high()
#    time.sleep(0.25)
#    lr.low()
#    x = sm.get()
#    print(hex(x))
#    time.sleep(0.25)

BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
D0D1D2D3D4D5D6D7GNDLOGIC