Created
September 23, 2022 04:40
-
-
Save makvoid/75a28d1c847e179a3e86fb10131d7f57 to your computer and use it in GitHub Desktop.
Internet-controllable LED Strip MicroPython code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from config import config | |
from machine import SPI, Pin | |
from micropython_dotstar import DotStar | |
from network import WLAN, STA_IF | |
from time import sleep, time | |
import uwebsockets.client | |
# Setup the network | |
... | |
# Limit a value between two values | |
def clamp(num, min_val, max_val): | |
return max(min(num, max_val), min_val) | |
# Helper function to create the websocket connection/timeout | |
def create_websocket(): | |
print('Creating websocket connection...') | |
try: | |
ws = uwebsockets.client.connect(config['ws_url']) | |
ws.settimeout(5) | |
except: | |
print(f'Error creating websocket, trying again shortly...') | |
sleep(config['ws_connection_delay']) | |
return create_websocket() | |
return ws | |
# Setup websocket connection | |
websocket = create_websocket() | |
# Setup SPI/DotStar | |
spi = SPI( | |
sck=Pin(config['sck_pin']), | |
mosi=Pin(config['mosi_pin']), | |
miso=Pin(config['miso_pin']) | |
) | |
dotstar = DotStar(spi, config['num_dotstars']) | |
# Wait for a websocket message | |
while True: | |
# Attempt to receive a message | |
msg = None | |
try: | |
msg = websocket.recv().replace('"', '').split(',') | |
except Exception as e: | |
print('Error during receive:', e) | |
# If we received a message, format the values and update the DotStar array | |
if msg: | |
# If we receive a blank message, this is most likely the websocket dropping | |
if len(msg) == 1: | |
websocket = create_websocket() | |
continue | |
# Format the tuple and set the color | |
color = ( | |
clamp(int(msg[0]), 0, 255), # Red | |
clamp(int(msg[1]), 0, 255), # Green | |
clamp(int(msg[2]), 0, 255), # Blue | |
clamp(float(msg[3]), 0, 1) # Brightness | |
) | |
dotstar.fill(color) | |
print('Color set to', color) | |
# Send a blank message (to help w/ closed sockets) | |
try: | |
websocket.send('') | |
except: | |
websocket = create_websocket() | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment