from machine import Pin, ADC, PWM, I2C
from ssd1306 import SSD1306_I2C
import utime

# OLED screen setup
WIDTH = 128
HEIGHT = 32
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=400000)
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)

# RGB LED PWM setup
RED_PIN = PWM(Pin(16))
GREEN_PIN = PWM(Pin(17))
BLUE_PIN = PWM(Pin(18))

# Set PWM frequency
RED_PIN.freq(1000)
GREEN_PIN.freq(1000)
BLUE_PIN.freq(1000)

# Potentiometers connected to ADC
pot_red = ADC(26)
pot_green = ADC(27)
pot_blue = ADC(28)

# Helper function to map ADC values (0-65535) to RGB (0-255)
def adc_to_rgb(value):
    return int(value / 65535 * 255)

# Main loop
while True:
    # Read potentiometer values
    red_val = pot_red.read_u16()
    green_val = pot_green.read_u16()
    blue_val = pot_blue.read_u16()

    # Map potentiometer values to 0-255 for RGB
    red = adc_to_rgb(red_val)
    green = adc_to_rgb(green_val)
    blue = adc_to_rgb(blue_val)

    # Set RGB LED color using PWM duty cycle (0-65535)
    RED_PIN.duty_u16(red_val)
    GREEN_PIN.duty_u16(green_val)
    BLUE_PIN.duty_u16(blue_val)

    # Clear the OLED screen
    oled.fill(0)

    # Display the current RGB values
    oled.text("RGB Color:", 0, 0)
    oled.text("({}, {}, {})".format(red, green, blue), 0, 10)

    # Update the OLED display
    oled.show()

    # Small delay to avoid flickering
    utime.sleep(0.1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT