# Benjamyn Love # Basic encoder controlled menu for setting the onboard neopixel # For the kb2040 # Pin connections # encoder_sw -> D3 # encoder_dt -> D4 # encoder_clk -> D5 # I2C_data -> A3 # I2C_clock -> A2 import math import board import adafruit_ssd1306 import neopixel import rotaryio import busio import digitalio import time # Setup the i2c bus i2c = busio.I2C(board.A3, board.A2) # Get the oled oled = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c) # Setup the NeoPixel neopixel = neopixel.NeoPixel(board.NEOPIXEL, 1) # Setup the encoder enc = rotaryio.IncrementalEncoder(board.D5, board.D4) # Setup the encoder button enc_btn = digitalio.DigitalInOut(board.D3) enc_btn.direction = digitalio.Direction.INPUT # Set strings SMT1 = "Set" SMT2 = "Colour :3" # Start the main loop last_position = None brightness = 1.0 menu_item = 0 sub_menu = False while True: if menu_item == 0: menu = "[R] G B !" if menu_item == 1: menu = "R [G] B !" if menu_item == 2: menu = "R G [B] !" if menu_item == 3: menu = "R G B [!]" # Get neopixel colour value current_r, current_g, current_b = neopixel[0] # Init the oled oled.fill(0) # Draw the menu oled.text(menu, 0, 0, 1) oled.text(SMT1 if sub_menu else " ", 100 - len(SMT1), 0, 1) oled.text(SMT2 if sub_menu else " ", 100 - len(SMT2), 10, 1) oled.text(f"{current_r}:{current_g}:{current_b}:{math.floor(neopixel.brightness * 100)}", 0, 10, 1) # Show the oled oled.show() if last_position is not None: # If we went right if enc.position > last_position: # Check if we are in the sub_menu if not sub_menu: if not (menu_item + 1) > 3: menu_item += 1 else: if menu_item == 0: if not (current_r + 1) > 255: current_r += 1 elif menu_item == 1: if not (current_g + 1) > 255: current_g += 1 elif menu_item == 2: if not (current_b + 1) > 255: current_b += 1 elif menu_item == 3: if not (brightness + 0.01) >= 1: brightness += 0.01 # If we went left elif enc.position < last_position: # Check if we are in the sub_menu if not sub_menu: if not (menu_item - 1) < 0: menu_item -= 1 else: if menu_item == 0: if not (current_r - 1) < 0: current_r -= 1 elif menu_item == 1: if not (current_g - 1) < 0: current_g -= 1 elif menu_item == 2: if not (current_b - 1) < 0: current_b -= 1 elif menu_item == 3: if not (brightness - 0.01) <= 0: brightness = brightness - 0.01 if not enc_btn.value: sub_menu = not sub_menu time.sleep(0.1) neopixel.fill((current_r, current_g, current_b)) neopixel.brightness = brightness last_position = enc.position