import machine
from rp2 import asm_pio, PIO
from machine import Pin
from FastADC import FastADC

@asm_pio()
def trigger():
    wait(0, pin, 0)
    wait(1, pin, 0)
    irq(0)
    push(block)

class Test:
    def __init__(self):
        self.fastadc = FastADC()
        self.adc_samples_captured = False
        self.fastsamples = None
        self.sm0 = PIO(1).state_machine(0)
        self.pin_trigger = Pin(14, Pin.IN)
        self.led_pin = Pin(7, Pin.OUT)
        
    def arm(self):
        self.sm0.init(trigger, freq=machine.freq(), in_base=self.pin_trigger)
        self.sm0.active(1)
        
    def arm_adc(self):
        self.adc_samples_captured = False
        self.sm0.irq(handler=self.__poll_fast_adc)
 
    @micropython.native
    def __poll_fast_adc(self, sm):
        print("triggered!")
        self.fastsamples = self.fastadc.read()
        self.adc_samples_captured = True
        self.led_pin.value(not self.led_pin.value())
    
    def block(self):
        print(f"*0x50200010 = {hex(machine.mem32[0x50200010])}")
        print(f"*0x50200030 = {hex(machine.mem32[0x50200030])}")
        print(f"*0x50200038 = {hex(machine.mem32[0x50200038])}")
        print(f"*0xE000E200 = {hex(machine.mem32[0xE000E200])}")
        # wait for the statemachine to finish
        while self.sm0.rx_fifo() == 0:
            pass
        print(f"*0x50200010 = {hex(machine.mem32[0x50200010])}")
        print(f"*0x50200030 = {hex(machine.mem32[0x50200030])}")
        print(f"*0x50200038 = {hex(machine.mem32[0x50200038])}")
        print(f"*0xE000E200 = {hex(machine.mem32[0xE000E200])}")
        
    def get_adc_samples(self):
        # wait for the adc to capture samples
        while not self.adc_samples_captured:
            pass
        print(self.fastsamples)
        
reset_pin = Pin(2, Pin.OUT)
test = Test()
while True:
    test.arm()
    test.arm_adc()
    reset_pin.value(0)
    reset_pin.value(1)
    test.block()
    test.get_adc_samples()


