import machine
import time

class MAX5822L:
    def __init__(self, i2c, address):
        self.i2c = i2c
        self.address = address
        self.write_register(0x0F, 0x00)  # Initialize the device

    def write_register(self, register, value):
        self.i2c.writeto(self.address, bytearray([register, value]))

    def power_down(self):
        self.write_register(0x0F, 0x01)
        time.sleep_ms(10)  # Allow time for power down

    def power_up(self):
        self.write_register(0x0F, 0x00)
        time.sleep_ms(10)  # Allow time for power up

    def set_voltage(self, channel, voltage):
        if channel < 0 or channel > 3:
            raise ValueError("Invalid channel. Channel must be between 0 and 3.")
        if voltage < 0 or voltage > 2.048:
            raise ValueError("Invalid voltage. Voltage must be between 0 and 2.048 V.")

        # Calculate DAC code based on voltage and resolution (12 bits)
        dac_code = int((voltage / 2.048) * 4095)

        # Write DAC code to the specified channel
        self.write_register(channel, dac_code >> 4)  # High byte
        self.write_register(channel + 0x04, (dac_code & 0x0F) << 4)  # Low byte

    def read_registers(self):
        # Read all registers (0x00 to 0x0F)
        registers = bytearray(16)
        self.i2c.readfrom_into(self.address, registers)
        return registers

# Example usage:
# Create an I2C object and initialize the MAX5822L DAC
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21))
dac = MAX5822L(i2c,0x70)

# # Set voltage on channel 0 to 1.0 V
# dac.set_voltage(0, 1.0)

# # Read all registers
# registers = dac.read_registers()
# print("Registers:", registers)

# # Power down the DAC
# dac.power_down()

# # Power up the DAC
# dac.power_up()

# # Set voltage on channel 1 to 1.5 V
# dac.set_voltage(1, 1.5)