使用AdafriutIO-dashboards控制Neopixel燈條—mpython

使用AdafriutIO-dashboards控制Neopixel燈條—mpython 

原本是打算使用Nord-RED或直接網頁控制,但還沒搞的很懂尤其寫網頁的部份,偶然在網路上搜到原來Adafruit也有出Dashboards
但是好像只能試用30天,但是沒關係,多認識一點不同的平台也很好

先到這裡註冊-https://io.adafruit.com/

接下來,我們在 Adafruit IO 中為 NeoPixels 的顏色創建
三個“紅色”、“藍色”和“綠色”。

然後點進去剛創建好的群組裡,接著下個步驟





最後,我們調整塊的設置。每個 RGB 值都是一個從 0 到 255 的整數。我們相應地配置滑塊。完成後,點擊“CREATE  BLOCK”。


API的key和username





程式的部份

from machine import Pin
from neopixel import NeoPixel
from time import sleep
import network
import urequests as requests
import ujson

# Wifi credentials
wifi_ssid = "C--"
wifi_password = "c----------"

# Adafruit IO authentication
aio_key = "aio_iaRV12GqVjk*************"
username = "bl-----"
headers = {'X-AIO-Key'aio_key'Content-Type''application/json'}

# Don't forget the NeoPixels!
np = NeoPixel(Pin(4), 8)
feed_names = ['red''green''blue']
rgb_values = {'red'0'green'0'blue'0}

# Connect to Wifi
def wifiConn():
  wifi = network.WLAN(network.STA_IF)
  wifi.active(True)
  wifi.connect(wifi_ssidwifi_password)
  while wifi.isconnected() == False:
      pass
  print("Conn successful!")
  
def create_URL(feedname):
    url = "https://io.adafruit.com/api/v2/" + username + "/feeds/" + feedname + "/data/last"
    return url

wifiConn()
while True:
  for colors in feed_names:
    res = requests.get(create_URL(colors), headers=headers)
    json = ujson.loads(res.text)
    rgb_values[colors] = int(json['value'])
    print(rgb_values[colors])
    for i in range(8):
      np[i] = (rgb_values['red'], rgb_values['green'], rgb_values['blue'])
      np.write()

數組 feed_names 包含我們在 Adafruit IO 中創建的提要的名稱,字典 rgb_values 用於存儲從 Adafruit IO 下載的值。

由於我們需要獲取三個提要的值,並且每個提要都有自己的 URL,因此我們創建了一個函數來生成所需的 URL。
def create_URL(feedname):
    url = "https://io.adafruit.com/api/v2/" + username +  "/feeds/" + feedname + "/data/last"
    return url

在主循環中,對於每個提要“紅色”、“綠色”和“藍色”,我們向 Adafruit IO 發送一個 HTTP GET 請求,其中包含由 create_URL 函數和標頭字典生成的 URL。
 response = requests.get(create_URL(color), headers=headers)

然後,我們使用 ujson 庫中的加載函數將從 Adafruit IO 接收到的 JSON 文本轉換為 Python 字典。這種轉換稱為解析。
parsed = ujson.loads(response.text)
從解析的 Python 字典中,我們得到提要的最新值(它是一個字符串)並將其轉換為整數。
value = int(parsed['value'])
將所有 RGB 值保存到字典 rgb_values 後,我們可以相應地設置 NeoPixels 的顏色。




參考---









































































留言

這個網誌中的熱門文章

天氣光環時鐘+農曆提醒(NODE-RED)專題作品-micropython