User Tools

Site Tools


raspberry-pi-pico-bluetooth-led

This is an old revision of the document!


Raspbery Pi Pico Bluetooth LED

Control LEDs over Bluetooth.

Wiring

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.

raspberry-pi-pico-bluetooth-led.1644525928.txt.gz · Last modified: 2022/02/10 21:45 by admin