#
# program to test MCP42xxx digital potentiometer using RP2040 pico board and micropython v1.20
#
# HW SPI interface 0 is used with default pins.
# Though MCP42xxx max SPI clock frequency is 10MHz, we use 400kHz for the bread board testing. Remark: 1MHz was working as well.
#
# HW setup:
# Connect both A pins of the MCP42xxx to 3.3V of the Pico board, both B Pins to ground.
# A voltage between 0 and 3.3V can be measured on the W (wiper) Pin(s), depending on user input for wiper value
#
# Quick reference guide:
# upon start of the program user is asked to provide input which potentiometer should be tested (one or both).
# a loop will be started, where user enters any number between 0 and 255 to set wiper value
# Ctrl-C ends the program and both potentiometers are SW reset (disabled).
#
# requires module mcp42xxx.py
#
# rev. 2-Sep-2023
# completed and tested 3-Sep-2023
# by wolf2018
#

from machine import SPI, Pin
import mcp42xxx


# define SPI chip select Pin and set Pin to high (inactive) on instatiation
CS_pin = Pin(17, Pin.OUT, value=1)

# instantiate HW SPI 0
spi = SPI(0, baudrate=400_000, bits=8, sck=Pin(18), mosi=Pin(19))

# instantiate digital potentiometer object
digi_pot = mcp42xxx.MCP42xxx(spi, CS_pin)

# welcome message
welcome_msg = "\33c   MCP42xxx digital dual potentiometer test program\n   ------------------------------------------------\n\n.....choose what Potentiometer to use, then enter wiper setting 0...255\n.....use Ctrl_C to exit program\n"

# main program

print(welcome_msg)

# loop until valid pot number is entered
while True:
    pot_nbr = int(input("please enter potentiometer number 0 or 1.  Enter 2 to adjust both pots: "))

    if pot_nbr in [0, 1, 2]:
        break
    else:
        print(" wrong potentiometer number - needs to be 0,1 or 2. \n\n")

# starting main loop
print("please enter a wiper value between 0 and 255")

try:
    while True:
        wiper = int(input("wiper_value 0...255 = "))

        if wiper < 0:
            wiper = 0
            print("value < 0, set value to 0")

        if wiper > 255:
            wiper = 255
            print("value > 255, set value to 255")

        digi_pot.write(wiper, pot_nbr)

except KeyboardInterrupt:
    print("\n\nGot Ctrl-C exiting program")

except ValueError as error:
    print(error)

finally:
    digi_pot.shut_down(2)
    print("finally: disabled both potentiometers, exiting ...")
