5.12 距離測定

超音波モジュールは、距離測定や物体検出に使用されます。このプロジェクトでは、モジュールをプログラムして障害物の距離を取得します。超音波パルスを送信し、それが跳ね返ってくるまでの時間を測定することで、距離を計算できます。これにより、距離に基づくアクションや障害物回避行動を実装することができます。

必要な部品

このプロジェクトには、以下のコンポーネントが必要です。

キット全体を購入すると確かに便利です。こちらがリンクです:

名前

このキットのアイテム

リンク

ESP32 Starter Kit

320+

ESP32 Starter Kit

以下のリンクから個別に購入することもできます。

コンポーネントの紹介

購入リンク

ESP32 WROOM 32E

BUY

ESP32カメラ拡張ボード

-

ジャンパーワイヤ

BUY

超音波モジュール

BUY

利用可能なピン

  • 利用可能なピン

    こちらは、このプロジェクトのためのESP32ボード上の利用可能なピンのリストです。

    入力用

    IO13, IO14, IO27, IO26, IO25, IO33, IO32, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

    出力用

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

回路図

../../_images/circuit_5.12_ultrasonic.png

ESP32は10秒ごとに超音波センサーのTrigピンに一連の方形波信号を送信します。これにより、超音波センサーは40kHzの超音波信号を外側に放出するよう促されます。前方に障害物がある場合、超音波波は反射して戻ってきます。

信号を送信してから受信するまでの時間を記録し、2で割って光速を掛けることで、障害物までの距離を求めることができます。

配線図

../../_images/5.12_ultrasonic_bb.png

コード

注釈

  • esp32-starter-kit-main\micropython\codes パスにある 5.12_ultrasonic.py ファイルを開くか、コードをThonnyにコピー&ペーストします。次に、「Run Current Script」をクリックするかF5キーを押して実行します。

  • 右下隅にある「MicroPython (ESP32).COMxx」インタプリタを選択してください。

import machine
import time

# Define the trigger and echo pins for the distance sensor
TRIG = machine.Pin(26, machine.Pin.OUT)
ECHO = machine.Pin(25, machine.Pin.IN)

# Calculate the distance using the ultrasonic sensor
def distance():
    # Ensure trigger is off initially
    TRIG.off()
    time.sleep_us(2)  # Wait for 2 microseconds

    # Send a 10-microsecond pulse to the trigger pin
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()

    # Wait for the echo pin to go high
    while not ECHO.value():
        pass

    # Record the time when the echo pin goes high
    time1 = time.ticks_us()

    # Wait for the echo pin to go low
    while ECHO.value():
        pass

    # Record the time when the echo pin goes low
    time2 = time.ticks_us()

    # Calculate the time difference between the two recorded times
    during = time.ticks_diff(time2, time1)

    # Calculate and return the distance (in cm) using the speed of sound (340 m/s)
    return during * 340 / 2 / 10000

# Continuously measure and print the distance
while True:
    dis = distance()
    print('Distance: %.2f' % dis)
    time.sleep_ms(300)  # Wait for 300 milliseconds before repeating

プログラムが実行されると、シェルは前方の障害物から超音波センサーまでの距離を出力します。