# 4. Relay_DHT11_WS2812 5050 RGB LED
<p style="text-align:right">Steven Lee</p>
## 繼電器(Relay)

* NO:Normal Open,常開,也就是正常情況它是不通電的。
* COM:Common Ground,共接電,很多人習慣把外電接到這個接腳,再從NO或NC接到外部設備上。
* NC:Normal Close,常閉,它在正常情況下是接通的。
* NO和NC一次只會選擇接一個
```python=
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
Sing =11
GPIO.setwarnings(False)
GPIO.setup(Sing,GPIO.OUT,initial=GPIO.LOW)
def do_action():
GPIO.output(Sing,True)
time.sleep(1)
GPIO.output(Sing,False)
time.sleep(1)
for i in range(1,5):
do_action()
```
## 溫溼度感測器(DHT11)

* 超低成本
* 3 至 5V 電源和 I/O
* 轉換期間最大電流使用2.5mA(請求數據時)
* 適用於 20-80% 濕度讀數,精度為 5%
* 適用於 0-50°C 溫度讀數±2°C 精度
* 不超過 1 Hz 採樣率(每秒一次)
* 體積小
```python=
import time
import Adafruit_DHT
GPIO_PIN = 4
humidity,temperature = 0.0,0.0
while True:
humidity,temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11,GPIO_PIN)
payload = {'temperature' : temperature , 'humidity' : humidity}
print (payload)
```
## 可程式控制RGB燈條(WS2812 5050 RGB LED)

```
pip install adafruit-circuitpython-neopixel
```


上圖充分解釋了 WS2812 傳資料的模式,舉個例子來解釋或許會比較清楚。假設我有 10 顆 WS2812 LED (先不論電壓電流等因素,只討論資料傳送),相當於要傳 240 bits 資料 (因為 1 顆 RGB LED 是 24 bits),送完後要拉 LOW 至少 50us 讓 WS2812 知道資料傳完了,如果沒有這個機制 (reset code),WS2812 會以為資料還沒送完,就不會顯示任何東西。
而這 240 bits 放進 LED 的方式,比如說用前 48 bits 來解釋的話即為,假設開頭的 48 bits 為
11111111 00101101 10001011 00100101 00011110 11001110……
第一個位置的 LED 所被放進的值就為 11111111 00101101 10001011。
然後原本的 48 bits 就會少掉 24 bits (因為給了第一個位置的 LED),變成 00100101 00011110 11001110,然後這 24 bits 又會被放到第二個位置的 LED,以此類推,直到拉 LOW 50us 表示資料傳送完畢,並且顯示出資料對應的數值顏色。
```python=
import time
import board
import neopixel
pixel_pin = board.D18
num_pixels = 32+16 #根據LED數量決定
ORDER = neopixel.GRB
pixels = neopixel.NeoPixel(
pixel_pin, num_pixels, brightness=0.2, auto_write=False, pixel_order=ORDER
)
def wheel(pos):
if pos < 0 or pos > 255:
r = g = b = 0
elif pos < 85:
r = int(pos * 3)
g = int(255 - pos * 3)
b = 0
elif pos < 170:
pos -= 85
r = int(255 - pos * 3)
g = 0
b = int(pos * 3)
else:
pos -= 170
r = 0
g = int(pos * 3)
b = int(255 - pos * 3)
return (r, g, b) if ORDER in (neopixel.RGB, neopixel.GRB) else (r, g, b, 0)
def rainbow_cycle(wait):
for j in range(255):
for i in range(num_pixels):
pixel_index = (i * 256 // num_pixels) + j
pixels[i] = wheel(pixel_index & 255)
pixels.show()
time.sleep(wait)
while True:
pixels.fill((255, 0, 0))
pixels.show()
time.sleep(1)
pixels.fill((0, 255, 0))
pixels.show()
time.sleep(1)
pixels.fill((0, 0, 255))
pixels.show()
time.sleep(1)
rainbow_cycle(0.001)
```
###### tags: `物聯網`