#!/usr/bin/env python3
# Control AD5206 digital potentiometer using SPI
# remind me to set geany from tabs to spaces
import spidev
import time
import RPi.GPIO as GPIO

# Setup the SPI connection
spi = spidev.SpiDev()
spi.open(0, 0)  # Bus 0, device 0 (Chip Select 0)
spi.max_speed_hz = 50000  # Set the SPI speed (adjust as needed)

# IO Chip Select pins
cs1 = 23
cs2 = 24
cs3 = 25

# Constants
MAX = 255
MIN = 0
MID = 127

# Setup GPIO for Chip Select (CS)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False) 
GPIO.setup(cs1, GPIO.OUT)  # Chip Select for AD5206 #1
GPIO.setup(cs2, GPIO.OUT)  # Chip Select for AD5206 #2
GPIO.setup(cs3, GPIO.OUT)  # Chip Select for AD5206 #3

# Function to write data to a specific channel of an AD5206
def set_pot(cs_pin, channel, value):
    if channel < 0 or channel > 5:
        raise ValueError("Channel must be between 0 and 5.")
    if value < 0 or value > 255:
        raise ValueError("Value must be between 0 and 255.")
    
    GPIO.output(cs_pin, GPIO.LOW)  # Enable the chip by pulling CS low
    # Command byte: Bits 2:0 for channel (0-5), others 0
    command_byte = channel & 0x07  # Ensure only the last 3 bits are used
    data = [command_byte, value]  # Command byte followed by value
    spi.xfer2(data)  # Send the data to the AD5206
    GPIO.output(cs_pin, GPIO.HIGH)  # Disable the chip by pulling CS high

print("AD5206 control program running. Press Ctrl+C to exit.")
print("I forget is 0  min brightness or max?")

# Enable all the devices for write
GPIO.output(cs1, GPIO.LOW)  # Enable the chip by pulling CS low
GPIO.output(cs2, GPIO.LOW)  # Enable the chip by pulling CS low
GPIO.output(cs3, GPIO.LOW)  # Enable the chip by pulling CS low
# Initialize all channels on all chips to minimum resistance
for channel in range(6):
    set_pot(cs1, channel, MIN)
    set_pot(cs2, channel, MIN)
    set_pot(cs3, channel, MIN)
# disable all the devices
GPIO.output(cs1, GPIO.HIGH)  # disable the chip by pulling CS high	
GPIO.output(cs2, GPIO.HIGH)  # disable the chip by pulling CS high	
GPIO.output(cs3, GPIO.HIGH)  # disable the chip by pulling CS high


# Test: Set channel 3 on each chip to MID resistance
#set_pot(cs1, 3, MID)
#set_pot(cs2, 3, MID)
#set_pot(cs3, 3, MID)

# Cleanup GPIO on exit
def cleanup():
    GPIO.cleanup()
    spi.close()

# Ensure GPIO cleanup on exit
try:
	
    while True:      
        # Example: Gradually increase channel 0 resistance on cs1
        for value in range(MIN, MAX + 1, 10):
            for n in range(6):
                set_pot(cs1, n, value)
               # print(f{value})
            time.sleep(0.1)
        for value in range(MIN, MAX + 1, 10):
            for n in range(6):
                set_pot(cs2, n, value)
                #print(f{value})
            time.sleep(0.1)
        for value in range(MIN, MAX + 1, 10):
            for n in range(6):
                set_pot(cs3, n, value)
                #print(f{value})
            time.sleep(0.1)                   
            
except KeyboardInterrupt:
    print("\nExiting program.")
finally:
    cleanup()
