Untitled
unknown
plain_text
9 months ago
2.3 kB
8
Indexable
import sys
import board
import neopixel
from Adafruit_IO import MQTTClient
# Your Adafruit IO credentials
ADAFRUIT_IO_KEY = 'aio_mSNC806Ei13CaL1NjVlk3uuCCo9t'
ADAFRUIT_IO_USERNAME = 'cytron'
FEED_KEY = 'control-neopixel' # Renamed feed key for clarity
# ----------------------
# NeoPixel Setup Section
# ----------------------
# Choose the GPIO pin that is connected to the NeoPixel's data input.
# GPIO18 is commonly used since it supports PWM.
pixel_pin = board.D18 # Adjust if you use a different pin
# Number of NeoPixel LEDs you have (change if more than one LED)
num_pixels = 1
# Pixel color channel order (often GRB for NeoPixels)
ORDER = neopixel.GRB
# Initialize the NeoPixel object:
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER)
# ----------------------
# MQTT Callback Functions
# ----------------------
def on_connect(client):
print(f"Connected to Adafruit IO, subscribing to {FEED_KEY}")
client.subscribe(FEED_KEY)
def on_disconnect(client):
print("Disconnected from Adafruit IO.")
sys.exit(1)
def on_message(client, feed_id, payload):
print(f"Feed {feed_id} received new value: {payload}")
# Turn the NeoPixel on (set to white) or off based on the payload:
if payload.lower() == "on":
# Set the NeoPixel to white; change the tuple to your desired color.
pixels[0] = (255, 255, 255)
pixels.show() # Update the LED with the new color
print("NeoPixel turned ON")
elif payload.lower() == "off":
# Turn off the NeoPixel by setting its color to black.
pixels[0] = (0, 0, 0)
pixels.show() # Update the LED with the new state
print("NeoPixel turned OFF")
else:
print("Unknown command received.")
# ----------------------
# MQTT Client Setup
# ----------------------
client = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
# ----------------------
# Start the MQTT Client Loop
# ----------------------
try:
client.connect()
client.loop_blocking()
except Exception as e:
print(f"Error: {e}")
Editor is loading...
Leave a Comment