This project is coded in CircuitPython. It utilizes the Adafruit Character LCD and NeoPixel libraries, so make sure that they are loaded into your library folder on your board.
# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
# SPDX-License-Identifier: MIT

import math
import time

import adafruit_character_lcd
import board
import digitalio
import neopixel
from analogio import AnalogIn

lcd_rs = digitalio.DigitalInOut(board.D5)
lcd_en = digitalio.DigitalInOut(board.D6)
lcd_d7 = digitalio.DigitalInOut(board.D12)
lcd_d6 = digitalio.DigitalInOut(board.D11)
lcd_d5 = digitalio.DigitalInOut(board.D10)
lcd_d4 = digitalio.DigitalInOut(board.D9)
lcd_columns = 16
lcd_rows = 2

lcd = adafruit_character_lcd.Character_LCD(
    lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows

potR = AnalogIn(board.A0)  # pot pin for R val
potG = AnalogIn(board.A1)  # pot pin for G val
potB = AnalogIn(board.A2)  # pot pin for B val
pixpin = board.D13  # neopixel pin
numpix = 8

strip = neopixel.NeoPixel(pixpin, numpix, brightness=0.1)

def val(pin):
    # divides voltage (65535) to get a value between 0 and 255
    return pin.value / 257

while True:
    strip.fill((int(val(potR)), int(val(potG)), int(val(potB))))
    # int converts float val to an integer

    lcd.set_cursor(3, 0)
    # text at the top of the screen
    lcd.message('R + G + B =')
    lcd.set_cursor(2, 1)
    # str converts float val to a string, trunc removes decimal values
    lcd.set_cursor(6, 1)
    lcd.set_cursor(10, 1)
    # refreshes screen to send updated values from pots

The goal of the code is to have the three potentiometers each control the red, green and blue values of the NeoPixels. The NeoPixels should update in real time according to the values read from the potentiometers and then those same values should appear on the LCD's screen.

The analog values produced by the potentiometers are converted to digital values by dividing the analog value by 257, giving a minimum value of 0 and a maximum value of 255. This value exists as a float. For the values to be able to be used as a value for the NeoPixels they need to be converted to integers with int.

For these same values to be used with the LCD screen, they need to be converted to strings, which is done with str. The only issue that remains is that the values will appear with their decimal points, making them incredibly long and unable to fit on the screen. The decimal is removed by using the truncate function (math.trunc) from the Python math library. Finally, lcd_clear() has to be called at the end of the loop so that the LCD refreshes to reflect the changing values from the potentiometers.

This guide was first published on Mar 02, 2018. It was last updated on Jul 20, 2024.

This page (RGB CircuitPython Code Using the NeoPixel Library) was last updated on Jul 20, 2024.

Text editor powered by tinymce.