注釈
こんにちは、SunFounderのRaspberry Pi & Arduino & ESP32愛好家コミュニティへようこそ!Facebook上でRaspberry Pi、Arduino、ESP32についてもっと深く掘り下げ、他の愛好家と交流しましょう。
参加する理由は?
エキスパートサポート:コミュニティやチームの助けを借りて、販売後の問題や技術的な課題を解決します。
学び&共有:ヒントやチュートリアルを交換してスキルを向上させましょう。
独占的なプレビュー:新製品の発表や先行プレビューに早期アクセスしましょう。
特別割引:最新製品の独占割引をお楽しみください。
祭りのプロモーションとギフト:ギフトや祝日のプロモーションに参加しましょう。
👉 私たちと一緒に探索し、創造する準備はできていますか?[ここ]をクリックして今すぐ参加しましょう!
2.2.7 超音波センサーモジュール¶
はじめに¶
超音波センサーは、物体を正確に検出し、距離を測定するために超音波を使用します。それは超音波を発信し、それらを電子信号に変換します。
必要な部品¶
このプロジェクトには、次のコンポーネントが必要です。
一式を購入するのが便利です、こちらがリンクです:
名前 |
このキットのアイテム |
リンク |
---|---|---|
Raphael Kit |
337 |
以下のリンクから別々に購入することもできます。
コンポーネントの紹介 |
購入リンク |
---|---|
回路図¶
実験手順¶
ステップ 1: 回路を組み立てます。
ステップ 2: コードのフォルダに移動します。
cd ~/raphael-kit/python-pi5
ステップ 3: 実行可能ファイルを実行します。
sudo python3 2.2.8_Ultrasonic_zero.py
コードを実行すると、超音波センサーモジュールが前方の障害物とモジュール自体の距離を検出し、その距離値が画面に表示されます。
コード
注釈
以下のコードを 変更/リセット/コピー/実行/停止 することができます。ただし、その前に raphael-kit/python_5
のソースコードパスに移動する必要があります。コードを変更した後、効果を確認するために直接実行できます。
#!/usr/bin/env python3
from gpiozero import DistanceSensor
from time import sleep
# Initialize the DistanceSensor using GPIO Zero library
# Trigger pin is connected to GPIO 23, Echo pin to GPIO 24
sensor = DistanceSensor(echo=24, trigger=23)
try:
# Main loop to continuously measure and report distance
while True:
dis = sensor.distance * 100 # Measure distance and convert from meters to centimeters
print('Distance: {:.2f} cm'.format(dis)) # Print the distance with two decimal precision
sleep(0.3) # Wait for 0.3 seconds before the next measurement
except KeyboardInterrupt:
# Handle KeyboardInterrupt (Ctrl+C) to gracefully exit the loop
pass
コードの説明
遅延用に
time
モジュールからsleep
関数を含む、距離測定用のgpiozero
ライブラリからDistanceSensor
クラスをインポートします。#!/usr/bin/env python3 from gpiozero import DistanceSensor from time import sleep
エコーピンをGPIO 24に、トリガーピンをGPIO 23に接続した超音波距離センサーを初期化します。
# Initialize the DistanceSensor using GPIO Zero library # Trigger pin is connected to GPIO 23, Echo pin to GPIO 24 sensor = DistanceSensor(echo=24, trigger=23)
メインループは距離を連続して測定し、メートルからセンチメートルに変換し、小数点以下2桁の精度で表示します。その後、0.3秒待ってから距離を再測定します。
KeyboardInterrupt
(Ctrl+Cのような)をキャッチしてスクリプトから gracefully に終了できるようにします。try: # Main loop to continuously measure and report distance while True: dis = sensor.distance * 100 # Measure distance and convert from meters to centimeters print('Distance: {:.2f} cm'.format(dis)) # Print the distance with two decimal precision sleep(0.3) # Wait for 0.3 seconds before the next measurement except KeyboardInterrupt: # Handle KeyboardInterrupt (Ctrl+C) to gracefully exit the loop pass