# 人體移動感應器(PIR)

人體移動感應器是很方便使用的電子模組元件，透過它可以偵測到附近是否有物體在移動，若有發現則觸發信號，電腦就可以利用這個觸發信號進行更進一步的活動，如閃燈、發出警告音等。

另外，日後的分享影音，將以gpiozero這個GPIO模組庫為主要對象，因為RPi GPIO是很底層的模組庫，要完成許多工作全部必須仰賴人工撰寫，因此在了解RPi GPIO的基本運作後，是時候離開它，並走向更方便的模組應用的時機了！

{% embed url="<https://youtu.be/mzRny98M4Qk>" %}

```python
from gpiozero import LED, MotionSensor
from signal import pause

led = LED(26)
ms = MotionSensor(17)

def some_one_here(pir):
    print('有人來了', pir.pin.number)
    led.blink(1, 0.5, 3)

ms.when_motion = some_one_here

pause()
```

如果是純使用RPi.GPIO，程式碼會變得較為煩人，但了解其底層的運作也不錯，程式碼如下，提供參考。

```python
import RPi.GPIO as gpio
from time import sleep

led = 26
pir = 17


def pir_checked(channel):
    print('some one here', channel)
    for i in range(3):
        gpio.output(led, gpio.HIGH)
        sleep(1)
        gpio.output(led, gpio.LOW)
        sleep(1)


gpio.setmode(gpio.BCM)

gpio.setup(led, gpio.OUT)
# 採用內建的下拉電阻
gpio.setup(pir, gpio.IN, gpio.PUD_DOWN)

try:
    # gpio.FALLING是指當電壓從高往下降時觸發事件
    # 這裡使用gpio.RISING是指當電壓從低往上升時觸發事件
    # 倒底要用哪個？會因為使用上拉或是下拉電阻的不同而不同。
    gpio.add_event_detect(pir, gpio.RISING, pir_checked, bouncetime=200)
    while True:
        sleep(1)
except KeyboardInterrupt:
    pass
gpio.cleanup()

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://s761111.gitbook.io/raspi-sensor/ren-yi-gan-qi-pir.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
