import rp2
from machine import Pin
import time
from FastADC import FastADC

# Define PIO program for SM0 to trigger an interrupt on button press
@rp2.asm_pio()
def button_irq():
    wrap_target()
    wait(0, pin, 0)
    wait(1, pin, 0)
    irq(block, 0)
    wrap()

# Initialize State Machine 0 for the button (GPIO 11)
button_pin = Pin(14, Pin.IN, Pin.PULL_DOWN)
sm_button = rp2.StateMachine(0, button_irq, freq=2000, in_base=button_pin)
led_pin = Pin(7, Pin.OUT)
fastadc = FastADC()
fastsamples = None
sampled = False

# Interrupt handler for the button press
def button_handler(sm):
    print("triggered")
    global sampled, fastsamples
    fastsamples = fastadc.read()
    led_pin.value(not led_pin.value())  # Toggle LED state
    sampled = True

# Attach the interrupt handler to the State Machine's IRQ
sm_button.irq(button_handler)
# Activate the state machine
sm_button.active(1)
 
# Keep the program running
while True:
    time.sleep(1)
    if sampled:
        print(fastsamples)
        sampled = False
