# MicroPython超音波HC-SR04

在這個單元使用的是以下這個超音波模組：

{% embed url="<https://www.taiwaniot.com.tw/product/hc-sr04/>" %}

在micro:bit的積木式環境如果要使用超音波模組的話，可以到擴充功能去啟用超音波的積木，而在MicroPython中也有熱心的程式設計師寫好可以直接匯入使用的模組了，此模組之連結如下：

{% embed url="<https://github.com/fizban99/microbit_hcsr04>" %}

使用方法很簡單，先到上面的網址下載專案檔案，在解壓縮之後找出一個叫做hcsr04.py的程式檔案，把這個檔案上傳到micro:bit板子上。在硬體方面，除了超音波模組的電源接妥之外，它的echo要接到micro:bit的第14支腳，trigger要接到micro:bit的第15支腳，連線完成之後，即可在REPL環境中輸入以下的程式進行測試：

```python
from hcsr04 import HCSR04
from microbit import *

sonar=HCSR04()
while True:
    print("{}cm".format(sonar.distance_mm()/10))
    sleep(1000)
```

上述程式執行之後，每隔一秒鐘會更新一次距離資訊，同學們可以用手在感測器前面試試它的效果如何喔。

{% hint style="info" %}
同學請特別留意，上面的那個程式是要在REPL環境下執行才看得到輸出的內容，因為它用的是print函數
{% endhint %}

以下的程式則是讓距離資料可以顯示在micro:bit的LED上，別忘了要使用display.scroll喔：

```python
from hcsr04 import HCSR04
from microbit import *

sonar=HCSR04()
while True:
    display.scroll("{}cm".format(sonar.distance_mm()/10))
    sleep(1000)
```

假設並不打算顯示數字，而是依照它所量測的距離來決定是否執行某些動作，可以透過繼電器來幫忙。繼電器有3支接腳，除了正負電源要連接到外部5V電源之外，它的S接線要連接到micro:bit的某一個輸出接腳，假設我們把它連到pin2的話，則程式可以編寫如下：

```python
from hcsr04 import HCSR04
from microbit import *

sonar=HCSR04()
while True:
    if sonar.distance_mm() < 50:
        pin2.write_digital(1)
        display.show(Image.HEART)
        sleep(500)
    else:
        pin2.write_digital(0)
        display.show(Image.HAPPY)
```

把這個程式燒錄進micro:bit之後，micro:bit會先顯示一個笑臉，當我們把障礙物慢慢靠近超音波感測器時，一旦低於5公分就會變成愛心圖案，並會聽到繼電器作動的聲音喔。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nkust.gitbook.io/micro-bit/micropython-chao-yin-bo-hcsr04.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
