在2014年時,曾使用 HC-SR501偵測移動的物體,當偵測的訊號時,亮綠燈。請參考這篇文章:Raspberry Pi 筆記(10):使用PIR (Passive Infrared)偵測物體移動。今天的實做是要將感測加上拍照功能,當偵測到物體移動時,綠色LED燈會亮,同時拍一張照片,間格10秒鐘,等待寫檔完成。以下就來看看要準備哪些材料及程式。
• HC-SR501 x 1
• Pi Camera x1
• LED x1
• 電阻 220K x1
• 連接線 x 5條
[材料]
• Raspberry Pi 2/3/4 x 1• HC-SR501 x 1
• Pi Camera x1
• LED x1
• 電阻 220K x1
• 連接線 x 5條
[線路連接與電路圖]
| Pi | HC-SR501 | LED |
|---|---|---|
| Pin 2(+5V) | VCC | - |
| Pin 6(GND) | GND | - |
| Pin 12(GPIO18) | OUT | - |
| Pin 1(+3.3V) | - | 接電阻,再連接LED正極 |
| Pin 16(GPIO23) | - | LED 負極 |
[程式]
變數 now 取得當時時間,並將時間當作檔名,這樣可以除了可以分辨照片的順序外,檔案名稱不會因重複而覆蓋先前的檔案。import RPi.GPIO as GPIO
import time
from datetime import datetime
from picamera import PiCamera
pir = 18
led_green = 23
camera = PiCamera()
GPIO.setmode(GPIO.BCM)
GPIO.setup(pir, GPIO.IN)
while True:
input_state = GPIO.input(pir)
if input_state == True:
print('Motion Detected')
GPIO.setup(led_green, GPIO.OUT)
now = datetime.now()
ptime = now.strftime("%Y_%m_%d_%H%M%S")
camera.capture('/home/pi/image_%s.jpg' % ptime)
print('A photo has been taken')
time.sleep(10)
else:
GPIO.setup(led_green, GPIO.IN)
camera.stop_preview()
[結果]
我將攝影機放在桌上,手一揮就拍下以下照片。[參考資料]
- Random Nerd tutorials:Raspberry Pi Motion Detector with Photo Capture


張貼留言