.. note::
こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。
**参加する理由は?**
- **エキスパートサポート**:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
- **学び&共有**:ヒントやチュートリアルを交換してスキルを向上させましょう。
- **独占的なプレビュー**:新製品の発表や先行プレビューに早期アクセスしましょう。
- **特別割引**:最新製品の独占割引をお楽しみください。
- **祭りのプロモーションとギフト**:ギフトや祝日のプロモーションに参加しましょう。
👉 私たちと一緒に探索し、創造する準備はできていますか?[|link_sf_facebook|]をクリックして今すぐ参加しましょう!
.. _4.1.5_py:
4.1.5 スマートビジュアルドアベル
==========================================
はじめに
-----------------
このプロジェクトでは、DIYのスマートビジュアルドアベルを作成しましょう。
必要な部品
------------------------------
このプロジェクトには、以下の部品が必要です。
.. image:: ../img/3.1.19components.png
:width: 800
:align: center
全セットを購入すると確実に便利です。リンクは以下です:
.. list-table::
:widths: 20 20 20
:header-rows: 1
* - 名前
- このキットのアイテム
- リンク
* - Raphael Kit
- 337
- |link_Raphael_kit|
以下のリンクから部品を別々に購入することもできます。
.. list-table::
:widths: 30 20
:header-rows: 1
* - コンポーネントの紹介
- 購入リンク
* - :ref:`cpn_gpio_board`
- |link_gpio_board_buy|
* - :ref:`cpn_breadboard`
- |link_breadboard_buy|
* - :ref:`cpn_wires`
- |link_wires_buy|
* - :ref:`cpn_resistor`
- |link_resistor_buy|
* - :ref:`cpn_button`
- |link_button_buy|
* - :ref:`cpn_audio_speaker`
- \-
* - :ref:`cpn_camera_module`
- |link_camera_buy|
回路図
-----------------------
============ ======== ======== ===
T-Board Name physical wiringPi BCM
GPIO27 Pin 13 2 27
============ ======== ======== ===
.. image:: ../img/3.1.19_schematic.png
:width: 500
:align: center
実験手順
------------------------------
**ステップ1:** 回路を作成します。
.. image:: ../img/3.1.19fritzing.png
:width: 800
:align: center
このプロジェクトを開始する前に、 :ref:`3.1.3_py` と :ref:`3.1.2_py` を完了していることを確認してください。
**ステップ2:** コードのフォルダに移動します。
.. raw:: html
.. code-block::
cd ~/raphael-kit/python/
**ステップ3:** 実行します。
.. raw:: html
.. code-block::
python3 4.1.5_DoorBell.py
コードが実行されると、次の動作が行われます:
- プログラムはドアベルボタンが押されるのを待機します。
- ボタンが押されると、ドアベル音が再生され、5 秒間の動画が録画されます。
- 録画された動画は、ユーザーのホームディレクトリに ``visitor.mp4`` として保存されます。
- システムは待機状態に戻り、次のボタン押下を待ちます。
- ``Ctrl+C`` を押すと終了し、使用したリソースが解放されます。
**コード**
.. note::
以下のコードを **修正/リセット/コピー/実行/停止** することができます。しかし、それをする前に、ソースコードのパス ``raphael-kit/python`` に移動する必要があります。コードを変更した後、その効果を直接見るために実行できます。
.. raw:: html
.. code-block:: python
#!/usr/bin/env python3
import time
import os
import RPi.GPIO as GPIO
from pygame import mixer
from picamera2 import Picamera2, Preview
from picamera2.encoders import H264Encoder
from picamera2.outputs import FfmpegOutput
# --------------------------------------------------
# USER DIRECTORY
# --------------------------------------------------
user = os.getlogin()
user_home = os.path.expanduser(f"~{user}")
# --------------------------------------------------
# CAMERA SETUP (Picamera2)
# --------------------------------------------------
camera = Picamera2()
# Create a video configuration WITHOUT the deprecated "video=" argument
video_config = camera.create_video_configuration(
main={"size": (1280, 720), "format": "XBGR8888"}
)
camera.configure(video_config)
# Create H264 encoder (10 Mbps is good quality for doorbell)
encoder = H264Encoder(bitrate=10_000_000)
# --------------------------------------------------
# GPIO SETUP
# --------------------------------------------------
BtnPin = 18
status = False
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
mixer.init()
def button_pressed(pin):
"""Button callback"""
global status
status = True
# --------------------------------------------------
# MAIN LOOP
# --------------------------------------------------
def main():
global status
GPIO.add_event_detect(BtnPin, GPIO.FALLING,
callback=button_pressed, bouncetime=250)
print("Doorbell system running... Press the button to record.")
while True:
if status:
print("Visitor detected!")
# Play doorbell sound
mixer.music.load(f"{user_home}/raphael-kit/music/doorbell.wav")
mixer.music.set_volume(0.7)
mixer.music.play()
# Use QTGL preview
camera.start_preview(Preview.QTGL)
# Output file
output_path = f"{user_home}/visitor.mp4"
output = FfmpegOutput(output_path)
# Start recording
camera.start_recording(encoder, output)
print(f"Recording video to {output_path}")
time.sleep(5) # Record for 5 seconds
# Stop everything
mixer.music.stop()
camera.stop_recording()
camera.stop_preview()
print("Recording finished.\n")
status = False
time.sleep(0.05)
# --------------------------------------------------
# CLEAN EXIT
# --------------------------------------------------
def destroy():
print("\nExiting...")
mixer.quit()
GPIO.cleanup()
camera.close()
print("Program exited cleanly.")
if __name__ == "__main__":
setup()
try:
main()
except KeyboardInterrupt:
destroy()
**コード説明**
#. 録画した動画を保存するため、現在のユーザーのホームディレクトリを取得します。
.. code-block:: python
user = os.getlogin()
user_home = os.path.expanduser(f"~{user}")
#. Picamera2 のインスタンスを作成し、動画録画用の設定を行います。
.. code-block:: python
camera = Picamera2()
video_config = camera.create_video_configuration(
main={"size": (1280, 720), "format": "XBGR8888"}
)
camera.configure(video_config)
#. GPIO18 に接続されたボタンをプルアップ入力として設定します。
.. code-block:: python
GPIO.setmode(GPIO.BCM)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#. ドアベル音の再生に使用するオーディオミキサーを読み込み、初期化します。
.. code-block:: python
mixer.init()
#. ボタンが押されたときに ``status`` を ``True`` に設定するコールバックを登録します。
.. code-block:: python
GPIO.add_event_detect(BtnPin, GPIO.FALLING,
callback=button_pressed, bouncetime=250)
#. ドアベル音を再生し、カメラのプレビューを開始、そして録画を開始します。
.. code-block:: python
mixer.music.load(f"{user_home}/raphael-kit/music/doorbell.wav")
mixer.music.play()
camera.start_preview(Preview.QTGL)
camera.start_recording(encoder, output)
#. 5 秒間動画を録画し、 ``visitor.mp4`` として保存します。
.. code-block:: python
time.sleep(5)
camera.stop_recording()
camera.stop_preview()
#. ``Ctrl+C`` でプログラムが停止したとき、すべてのリソースを解放します。
.. code-block:: python
mixer.quit()
GPIO.cleanup()
camera.close()
現象の画像
------------------------
.. image:: ../img/4.1.5door_bell.JPG
:align: center