# MicroPython伺服馬達操作

伺服馬達可以透過角度的方式讓馬達指定到固定的位置，對於控制一些機構的情況非常方便。第一個練習使用的是下面這顆伺服馬達：

{% embed url="<https://www.taiwaniot.com.tw/product/%E8%BC%9D%E7%9B%9B-sg90-tower-pro-1-8kg-%E8%88%B5%E6%A9%9F-9%E5%85%8B%E4%BC%BA%E6%9C%8D%E6%A9%9F/>" %}

大部份的伺服馬達都有三條線，分別是電源線的正負極（因為伺服馬達需要較大電流，所以也是要額外供電喔），以及一條決定要轉幾度的訊號線，而對於要控制它的角度的micro:bit來說，連接控制用的腳位需要有PWM能力，也就是以數位信號模擬類比信號的技術。micro:bit只有pin3, pin4, 以及pin10這三支接腳具備此能力，還記得micro:bit的接腳圖嗎？請參考以下的說明：

{% embed url="<https://microbit-micropython.readthedocs.io/en/latest/pin.html?highlight=PWM>" %}

但是這3支接腳都和LED是共用的，所以為了使用這幾支接腳，要先把LED關閉才能。以下是測試的程式（假設把伺服馬達的信號號連接到pin3）：

```python
from microbit import *

display.off()
while True:
    pin3.write_analog(60)
    sleep(500)
    pin3.write_analog(120)
    sleep(500)
```

執行上面這個程式，你有就可以看到伺服馬達以0.5秒為間隔，很快地在兩個不同的角度間轉動。

還記得前一個使用光感測器的單元嗎？結合光感測器，我們就可以利用不同的亮度來決定伺服馬達的轉動角度，這個方式就可以用來製作雷射光打靶遊戲喔。

```python
from ssd1306 import initialize, clear_oled
from ssd1306_text import add_text
from microbit import *

display.off()
initialize()
clear_oled()
add_text(0, 0, 'NKUST')
add_text(0, 1, 'Richard Ho')

pin3.write_analog(120)
while True:
    light = pin1.read_analog()
    add_text(0, 3, 'Light:{:>4d}'.format(light))
    if light < 300:
        pin3.write_analog(60)
        sleep(5000)
    else:
        pin3.write_analog(120)
```

上面這個程式會把伺服馬達固定在某一個點上，當偵測到亮度小於300的時候，就會讓伺服馬達轉動到另外一個角度並停留5秒才再偵測是否需要回復到原有的角度。此外，為了讓我們可以隨時瞭解亮度的數值以方便調整程式，在程式中匯入了ssd1306，驅動OLED顯示器顯示出數值內容。

![](/files/-LfFecJvse0g-5pmh_Ns)


---

# 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-si-fu-cao-zuo.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.
