# ain_speed_test.py

# Raspberry Pi Pico - Analog Input Speed Test

# Read an analog input with the ADC and measure the number of conversions
# possible per second from CircuitPython.  The underlying hardware
# on the RP2040 chip is rated up to 500 kS/sec.

# Result: actual single-channel conversion rates run about 63 kS/sec.
# As a control case, an empty loop runs at around 192 kHz.

import board
import time
import analogio

#---------------------------------------------------------------
# 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)

#---------------------------------------------------------------
# Run the main loop: script equivalent to Arduino loop()

while True:

    # Read a single ADC channel many times in a tight loop.
    num_samples = 100000    
    start = time.monotonic_ns()
    for i in range(num_samples):
        sensor_level = sensor.value
    end = time.monotonic_ns()
    elapsed = 1e-9 * (end - start)
    rate = num_samples / elapsed
    print(f"Read {num_samples} samples in {elapsed} seconds, {rate} samples/sec.")

    # Pause briefly.
    time.sleep(1)
    
    # Control case: null loop
    start = time.monotonic_ns()
    for i in range(num_samples):
        pass
    end = time.monotonic_ns()
    elapsed = 1e-9 * (end - start)
    rate = num_samples / elapsed    
    print(f"Performed empty loop {num_samples} times in {elapsed} seconds, {rate} loops/sec.")

    # Pause briefly.
    time.sleep(1)
