# analog_input.py

# Raspberry Pi Pico - Analog Input demo

# Read an analog input with the ADC, drive the onboard LED, and print messages
# to the serial console only when the input state changes.

import board
import time
import analogio
import digitalio

#---------------------------------------------------------------
# Set up the hardware: script equivalent to Arduino setup()

# Set up built-in green LED for output.
led = digitalio.DigitalInOut(board.LED)  # GP25
led.direction = digitalio.Direction.OUTPUT

# Set up an analog input on ADC0 (GP26), which is physically pin 31.
# E.g., this may be attached to photocell or photointerrupter with associated pullup resistor.
sensor = analogio.AnalogIn(board.A0)

# These may be need to be adjusted for your particular hardware.  The Pico has
# 12-bit analog-to-digital conversion so the actual conversion has 4096 possible
# values, but the results are scaled to a 16-bit unsigned integer with range
# from 0 to 65535.
lower_threshold =  8000
upper_threshold = 45000

#---------------------------------------------------------------
# Run the main loop: script equivalent to Arduino loop()

# The following logic detects input transitions using a state machine with two
# possible states.  The state index reflects the current estimated state of the
# input.  The transition rules apply hysteresis in the form of assymmetric
# thresholds to reduce switching noise: the sensor value must rise higher than
# the upper threshold or lower than the lower threshold to trigger a state
# change.
state_index = False

while True:

    # Read the sensor once per cycle.
    sensor_level = sensor.value

    # uncomment the following to print tuples to plot with the mu editor
    # print((sensor_level,))
    # time.sleep(0.02)  # slow sampling to avoid flooding
    
    if state_index is False:
        if sensor_level < lower_threshold:
            led.value = True
            state_index = True
            print("On")

    elif state_index is True:
        if sensor_level > upper_threshold:
            led.value = False
            state_index = False
            print("Off")

    
