---
# System prepended metadata

title: <center>3. 光敏電阻_溫度傳感器_雨滴傳感器_⼟壤溼度傳感器</center>
tags: [物聯網]

---

# <center>3. 光敏電阻_溫度傳感器_雨滴傳感器_⼟壤溼度傳感器</center>
<p style="text-align:right">Steven Lee</p>


## 光敏電阻(Photoresistor)
![](https://i.imgur.com/bHO6Ibc.png)
- 利⽤光電導效應的⼀種特殊的電阻，和入射光的強弱有直接關係。
- 光強度增加，則電阻減⼩；光強度減⼩，則電阻增⼤。
    - V = I * R
- 容易受溫度影響
- ⽀持數位與類比的輸出
- 靈敏度可調
- 採⽤LM393、負光敏電阻
- 輸入電壓: DC 3~5V
- 數位輸出D0, 光線亮度達不到設定閥值, D0輸出⾼電位


![](https://i.imgur.com/kZBneLI.png)
``` python=
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(3, GPIO.IN)
while True:
    val = GPIO.input(3)
    if val == 0:
        print(f"Light exceeds threshold, value is {val}")
    else:
        print(f"Light is under threshold, value is {val}")
    time.sleep(1)
```

## 練習: 結合pcf8591使⽤類比輸入來偵測光線強度
## 溫度傳感器
- DS18B20 單匯流排數位溫度感測器模組
- [DS18B20 Datasheet](https://www.alldatasheet.com/datasheet-pdf/pdf/227472/DALLAS/DS18B20.html)

![](https://i.imgur.com/BVVm6Ju.png)
- 安裝w1thermsensor python library
```
sudo pip install w1thermsensor
```
![](https://i.imgur.com/H0Qp3Dt.png)

- DS18B20使⽤1 wire serial interface. (請確保1-wire 已啟⽤)
    - Raspberry Pi 與 DS18B20 之間事先講好的溝通規則
![](https://i.imgur.com/w0iMPIc.png)
- [w1thermsensor github](https://github.com/timofurrer/w1thermsensor)

![](https://i.imgur.com/LSnIqCD.png)
![](https://i.imgur.com/DdVmuD5.png)

- [one-wire interface on Raspberry Pi](https://pinout.xyz/pinout/1_wire)

![](https://i.imgur.com/IrFlrAQ.png)

``` python=
import time
from w1thermsensor import W1ThermSensor
sensor = W1ThermSensor()
while True:
    temperature = sensor.get_temperature()
    print("The temperature is %s celsius" % temperature)
    time.sleep(1)
```

## 雨滴傳感器
![](https://i.imgur.com/0srt801.png)

* ⼤⾯積型⽔滴雨⽔感測器
* 模擬類比輸出與數位輸出
* ⼯作電壓3.3V-5V
* 感應板上沒有⽔滴時， DO輸出為⾼電位
* 感應板上有⽔滴時， DO輸出為低電位
* 靈敏度可調

```python=
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(5, GPIO.IN)
while True:
    val = GPIO.input(5)
    if val == 0:
        print(f"water detected")
    else:
        print(f"no water")
    time.sleep(0.5)

```
## 思考如何利⽤此模組做⽔位偵測
## 練習: 結合pcf8591使⽤類比輸入來偵測⽔量
## ⼟壤溼度傳感器

![](https://i.imgur.com/fsaRREH.png)

* 測量⼟壤相對含⽔量
* 靈敏度可調
* ⽔分越多，⼟壤導電越容易(電阻越⼩)
* ⼟壤乾燥，導電越差(電阻越⼤)
* ⼯作電壓3.3V-5V
* 模擬類比輸出與數位輸出

```python=
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)
while True:
    val = GPIO.input(12)
    if val == 0:
        print(f"soil warter detected")
    else:
        print(f"no water")
    time.sleep(0.5)
```

## 練習: 結合pcf8591使⽤類比輸入來偵測⼟壤溼度
###### tags: `物聯網`