User Tools

Site Tools


raspberry-pi-pico-bluetooth-led

Raspbery Pi Pico Bluetooth LED

Control LEDs over Bluetooth. You can set RGB values and brightness. Brightness is calculated which is not perfect but does the job for now.

Wiring

radiopico-bluetooth-led.fzz

Parts

The Code

main.py
import json
import neopixel
from led import Led
from machine import UART, Pin
 
uart = UART(0, 9600)
led = Led()
 
while True:
    if uart.any():
        received = uart.read()
        try:
            input = received.decode("utf-8")
            payload = json.loads(input)
            command: str = payload["command"] 
        except:
            # Return command in case of decoding error
            # so the script does not break
            command: str = "error"
 
        if command == "on":
            R,G,B,brightness = payload["data"]["r"] , payload["data"]["g"], payload["data"]["b"], payload["data"]["brightness"]
            led.on(int(R), int(G), int(B), int(brightness))
            status: str = led.status()
            uart.write(status.encode("utf-8"))
 
        elif command == "off":
            led.off()
            status: str = led.status()
            uart.write(status.encode("utf-8"))
 
        elif command == "status":
            status = led.status()
            encoded = status.encode("UTF-8")
            uart.write(encoded)
        elif command == "error":
            print(received)
led.py
import time
from machine import Pin
import neopixel
import json
 
class Led:
    pin = Pin(13) # Pico GPIO13 (number 17)
    count = 39 # Number of LEDs on the strip
    state = {"command": "state", "state": 0, "r": 0, "g": 0, "b": 0, "brightness": 0}
    initialState = state
    strip = neopixel.NeoPixel(pin, count)
 
    def on(self, R: int, G: int, B: int, brightness: int = 100):
        strip = self.strip
 
        for i in range(self.count):
            strip[i] = (round(R * brightness / 100), round(G * brightness / 100), round(B * brightness / 100))
            strip.write()
            time.sleep(0.02)
        self.state = {"command": "state", "state": 1, "r": R, "g": G, "b": B, "brightness": brightness}
 
    def off(self):
        strip = self.strip
 
        for i in range(39):
            strip[i] = (0, 0, 0)
        strip.write()
        strip = self.initialState
 
    def status(self):
        return json.dumps(self.state)

Download the neopixel.py module.

Send commands

https://play.google.com/store/apps/details?id=de.kai_morich.serial_usb_terminal&hl=de&gl=US

Turn on

{"command": "on", "data": {"r": 255, "g": 255, "b": 255, "brightness": 100}}

Turn off

{"command": "off"}

Get LED state:

{"command": "status"}
raspberry-pi-pico-bluetooth-led.txt · Last modified: 2022/02/10 22:42 by admin