# soft_analog.py

# Demonstrate measurement of an analog soft sensor input using the Crickit.
# This is intended to attach to an external soft touch sensor hand-fabricated
# using conductive fabric and Velostat.  The electrical resistance of the sensor
# varies with pressure.

# The wiring for this is as follows:
#  1. One half of sensor connected to GND (either half).
#  2. Other half of sensor connected to Signal 1.
#  3. External resistor connects between Signal 1 and 3.3V.

# This example uses three pins from the Signal I/O section of the Cricket:
# Signal 1, +3.3V, and GND.  An external resistor (typically 10K) should be
# connected between the 3.3V pin and Signal 1, and the conductive sensor between
# Signal 1 and GND.  The resistor will provide a small current to create a
# voltage across the sensor which will vary with pressure.  E.g., it will form
# one leg of a voltage divider with the sensor.

# As mechanical pressure is applied, the sensor resistance drops along with the
# voltage across the sensor.  Please note that the sensor voltage follows an
# inverse logic: when not pressed, the input value will be midrange, and when
# pressed, it will drop (possibly to zero).

# ----------------------------------------------------------------
# Import the standard Python time functions.
import time

# Import the Crickit interface library.
from adafruit_crickit import crickit

# Calculate the scaling coefficient to translate the raw analog value into volts.
scaling = 3.3 / (2**10)

# ----------------------------------------------------------------
# Begin the main processing loop.
while True:

    # Read the integer sensor value and scale it to a value in Volts.
    volts = crickit.seesaw.analog_read(crickit.SIGNAL1) * scaling
    
    # Every handmade sensor will have different properties, so the
    # interpretation of the voltage value will usually need to be individually
    # calibrated.  One way to accomplish this is by measuring the voltage
    # response under different conditions, then applying additional scaling and
    # offset to produce a normalized signal (possibly inverted).  For example,
    # if the observed voltage ranges between 1.4 and 0.1 Volts, the input signal
    # could be normalized to a [0,1] range as follows:
    pressure = (1.4 - volts) / (1.4 - 0.1)

    # Print the voltage reading and normalized value on the console.
    print(f"({volts}, {pressure})")
    
    # Limit the rate of the main loop.
    time.sleep(0.1)
