> For the complete documentation index, see [llms.txt](https://mbyzhang.gitbook.io/loongbian/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mbyzhang.gitbook.io/loongbian/io/adafruit-blinka-library/sample-programs/hcsr04-sonic.md).

# 板载 GPIO：HC-SR04 超声波传感器

本样例使用了一个连接到板载 GPIO 接口的 HC-SR04 超声波传感器模块。Python 程序将会持续获取传感器测得的距离，并输出到控制台中。

## 硬件连线

| 模块角标 | 龙芯派接口      | Python 引脚常量名 |
| ---- | ---------- | ------------ |
| VCC  | P2: P5V    |              |
| TRIG | P13: GPIO2 | GPIO2        |
| ECHO | P15: GPIO3 | GPIO3        |
| GND  | P9: GND    |              |

## 软件依赖

该样例依赖 Adafruit CircuitPython HC-SR04 驱动库，可使用如下命令安装。

```
$ su -
$ apt install python3-pip
$ pip3 install -U adafruit-circuitpython-hcsr04
```

## 代码

```python
import time
import board
import adafruit_hcsr04

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.GPIO2, echo_pin=board.GPIO3)

while True:
    try:
        print(sonar.distance)
    except RuntimeError as e:
        print(e)
    time.sleep(1)
```

程序运行后，程序应持续输出超声波传感器测得的距离。

{% hint style="warning" %}
&#x20;由于 HC-SR04 传感器使用了 5v 电平，而龙芯派 IO 使用了 3.3v 电平。为避免损坏龙芯派，建议将传感器的 ECHO 引脚和龙芯派的 GPIO3 引脚之间进行 5v 至 3.3v 的电平转换。
{% endhint %}
