Skip to main content

7.3. RGB LED Controller

Under construction
Short example demonstration video

Project which uses Red, Green and Blue LED that light up depending on the resistance measured by photoresistor.

At the end of this example you will learn:

  • How to read analog value from photoresistor
  • How to control the LEDs displaying various colours
ℹ️

Parts required:

  • Soldered NULA Mini Board
  • Breadboard
  • 1 x Red, Green, Blue LED
  • 3 x 330Ω resistors
  • 1 x 10kΩ resistor
  • 1 x Photoresistor
  • Some jumper wires
Under construction
Required components

Putting the components together

  • Place the buzzer on the breadboard, connect the positive pin on GPIO 19, and other pin to GND.
  • For each pushbutton, place it on the breadboard, connect one terminal of the button to the pin declared in code, and the other terminal to GND using jumper wires.
  • Connect the LCD using Qwiic cable
Under construction
Components connected together

Code Example

Import necessary modules.

from machine import Pin, ADC, PWM
import time

Define pins for LEDs and photoresistor

LDR_PIN = 5       # Analog input pin for photoresistor
RED_PIN = 2 # PWM pin for red LED channel
GREEN_PIN = 3 # PWM pin for green LED channel
BLUE_PIN = 4 # PWM pin for blue LED channel

Declare ADC object for photoresistor and PWM objects for LEDs.

adc = ADC(Pin(LDR_PIN))

pwm_r = PWM(Pin(RED_PIN), freq=PWM_FREQ)
pwm_g = PWM(Pin(GREEN_PIN), freq=PWM_FREQ)
pwm_b = PWM(Pin(BLUE_PIN), freq=PWM_FREQ)
PWM_FREQ = 1000 # PWM frequency in Hz

Function to map value from one range to another.

def map_range(x, in_min, in_max, out_min, out_max):
if in_max == in_min:
return out_min
val = (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min
return max(min(val, max(out_min, out_max)), min(out_min, out_max))

Main loop that reads LDR value and lights up LEDs based on that value.

# Main loop
while True:
# Read LDR value
ldr_value = adc.read()
print("LDR value:", ldr_value)

# Map LDR value to RGB colors
if ldr_value <= 1365:
# Dark -> Red to Green
r = map_range(ldr_value, 0, 1365, 255, 0)
g = map_range(ldr_value, 0, 1365, 0, 255)
b = 0
elif ldr_value <= 2730:
# Medium light -> Green to Blue
r = 0
g = map_range(ldr_value, 1366, 2730, 255, 0)
b = map_range(ldr_value, 1366, 2730, 0, 255)
else:
# Bright -> Blue to White
r = map_range(ldr_value, 2731, 4095, 0, 255)
g = map_range(ldr_value, 2731, 4095, 0, 255)
b = 255

# Write PWM values to RGB pins
pwm_r.duty(int(r * 1023 / 255))
pwm_g.duty(int(g * 1023 / 255))
pwm_b.duty(int(b * 1023 / 255))

# Print RGB values
print("RGB:", r, g, b)

# Small delay
time.sleep_ms(100)