ESP32で距離センサ(HC-SR04)を使い，指向性を向上させる

# はじめに
 超音波センサモジュール(HC-SR04)とESP32を使って距離を測る.
![hcsr04.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/650453/15f1ec28-0dcf-bd69-ba76-73bf2f9093fe.png)

# 準備するもの

使用するデバイス：ESP32
使用するセンサ：HC-SR04
開発環境：micropython

# 接続方法

# コード


####距離センサHC-SR04の設定コード

```php:HC_SR04.py
import machine, time
from machine import Pin
import time 
import framebuf
import sys
from micropython import const

class HCSR04:
    # echo_timeout_us is based in chip range limit (400cm)
    def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30):
        """
        trigger_pin: Output pin to send pulses
        echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor
        echo_timeout_us: Timeout in microseconds to listen to echo pin. 
        By default is based in sensor limit range (4m)
        """
        self.echo_timeout_us = echo_timeout_us
        # Init trigger pin (out)
        self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None)
        self.trigger.value(0)
 
        # Init echo pin (in)
        self.echo = Pin(echo_pin, mode=Pin.IN, pull=None)
 
    def _send_pulse_and_wait(self):
        """
        Send the pulse to trigger and listen on echo pin.
        We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received.
        """
        self.trigger.value(0) # Stabilize the sensor
        time.sleep_us(5)
        self.trigger.value(1)
        # Send a 10us pulse.
        time.sleep_us(10)
        self.trigger.value(0)
        try:
            pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us)
            return pulse_time
        except OSError as ex:
            if ex.args[0] == 110: # 110 = ETIMEDOUT
                raise OSError('Out of range')
            raise ex
 
    def distance_cm(self):
        """
        Get the distance in centimeters with floating point operations.
        It returns a float
        """
        pulse_time = self._send_pulse_and_wait()
 
        # To calculate the distance we get the pulse_time and divide it by 2 
        # (the pulse walk the distance twice) and by 29.1 becasue
        # the sound speed on air (343.2 m/s), that It's equivalent to
        # 0.034320 cm/us that is 1cm each 29.1us
        cms = (pulse_time / 2) / 29.1
        return cms
```

#### 距離センサHC-SR04の実行コード
```
from HC_SR04 import HCSR04
from machine import Pin,I2C
from utime import sleep 
import math

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)      #Init i2c
 
sensor = HCSR04(trigger_pin=17, echo_pin=16,echo_timeout_us=1000000)

b=[]

try:
  for i in range(20):
    distance = sensor.distance_cm()
    
    a=int(distance)
    print(f"{a}"+"cm")
    b.append(a)
  print(b)
  
except KeyboardInterrupt:
       pass    
```



# 実行結果
- 目標物を60cm先に置いた
![qiitakiso.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/650453/78d36fc4-65fc-3e39-f2f8-8f5f8b17aada.png)
精度90%以上になりました.

- 目標物を200cm先に置いた

![tutunasi200.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/650453/5668cf08-55cb-c8c9-c0f7-8bb9559d95e8.png)


200cmに音波が到達しなかった．おそらく，目標物までの障害物に音波が干渉したと思われる．
干渉しないように指向性の実験をする．


# 指向性
距離センサの送信側に10cmの筒を付けた.
![指向性送信側.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/650453/0abb5825-d114-9eaa-a1d8-7438e49190c7.jpeg)

- 筒を付けたときの精度
![soushin200.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/650453/f7941825-3672-8f3d-4e2e-21c5eba7b001.png)


精度70%まで向上した．

# まとめ
超音波センサは15°の指向性があるため、対象物が遠くにある場合は筒を付けた方が良いことが分かった.
以上.