# 超音波測距實習

這次的主角，HC-SR04，正反面的照片如下：

![](/files/-LQ1zvkY6oIYzTX_RFnp)

![](/files/-LQ2--AbrIa_ZMvVYyOk)

它的4支接腳中，Vcc需要5V的電源，而Gnd當然直接接地就可以了。另外，Trig和Echo可以分別接到P0和P1，到時候在積木中可以指定。由於micro:bit只能供應3.3V的電源，所以我們使用了外部的電源，此外，由於我們打算把結果顯示在前一單元的OLED上，因此之前的電路就留著，不需要重新，但是我們把電源的部份都連接到麵包板上的電源匯流排了。

電路連接的樣子如下所示：

![](/files/-LQ2-y3B7rpWT9lYdEoH)

電路連接完畢之後回到micro:bit的程式開發環境中，也是一樣到擴展積木的地方，然後輸入sonar再搜尋，即可看到如下所示的畫面：

![](/files/-LQ20Nw4ywp1DsLuE8bq)

我們選用左邊這個，過一會兒就可以在環境中看到Sonar的積木了，如下所示：

![](/files/-LQ20azGJlI9ceDhrtN6)

Sonar只有一個積木，就是直接取得想要的資訊：

![](/files/-LQ20qfAjUXWOGhdY-ln)

只要設定trig以及echo的連接接腳以及想要的傳回值，就可以直接把它指定到某一個變數中再拿出來使用即可。以下是我們的測距程式：

![](/files/-LQ21U6wN9lye7F16bt8)

這個程式每隔2秒鐘就會更新一次偵測到的距離，非常方便喔。

![](/files/-LQ221QkaQgH2PnIHz_Q)


---

# 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/chao-yin-bo-ju.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.
