# MicroPython輸出入接腳控制

以下的程式是用來偵測第0支輸出入接腳（pin0, P0）是某導通，如果你在那個接腳加上一個實際的按鈕，就可以用來偵測該按鈕是否有被按下去過。

```python
from microbit import *

display.show(Image.HAPPY)
while True:
    if pin0.is_touched():
        display.show(Image.HEART)
```

當第一眼看到micro:bit時，不知道同學們是否被那麼多金屬的接腳吸引到？雖然不是每一支接腳都可以拿來作為輸出入使用，但是可以用的接腳其實也夠多了。先來看看接腳有哪些：

![](https://microbit.org/images/microbit-pins.jpg)

利用擴充接頭和麵包板，這次我們接出4個LED並排如下：

![](/files/-LeUd4XiA7xAk-9To4IZ)

程式如下：

```python
from microbit import *

leds = [pin0, pin1, pin2, pin8]
while True:
    for led in leds:
        led.write_digital(1)
        sleep(200)
        led.write_digital(0)
```

在程式的第3行中同學們有沒有注意到我們使用的腳位？從pin0, pin1, pin2，接下來是pin8？第4個LED沒有使用pin4的原因是它其實有其它的用途。事實上，3, 4, 6, 7, 9, 10是和板子上的LED矩陣共用的，而第5和第11個pin則是按鈕A和按鈕B，所以我們在輸出時就把這幾個接腳避開了。不過，如果接腳真的不夠用的話，把display（也就是LED矩陣）關閉的話，那幾支和它共用的接腳就可以使用了。接下來我們就把LED關閉，外接上8個LED試試，請看以下的連接照片：

![](/files/-LejLK775-Wj29HeLfoA)

在這個例子中我們就把LED矩陣顯示器先關閉，程式編寫如下：

```python
from microbit import *

leds = [pin0, pin1, pin2, pin3, pin4, pin6, pin7, pin8]
display.off()
while True:
    for led in leds:
        led.write_digital(1)
        sleep(50)
        led.write_digital(0)
    for led in reversed(leds):
        led.write_digital(1)
        sleep(50)
        led.write_digital(0)    
```

在這個程式中的第3行裡面的leds串列中詳列了所有要用來外接顯示LED的針腳，從pin0到pin8，中間只有pin5被跳過，原因是這個針腳是和按鈕A共用的，所以並不適合拿來做輸出信號之用。另外，和前一支程式不同的地方在於我們加上了一個迴圈（第10行到第13行），這個迴圈進行LED反向顯示的功能，如此就可以讓程式可以正反來回顯示LED燈號。程式的執行結果如下：

{% embed url="<https://youtu.be/drm8vromOi8>" %}


---

# 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-chu-ru-jie-kong-zhi.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.
