# 用Python點亮LED

## 一、歐姆定律與電阻分壓

學習電子學的歐姆電律與電阻分壓概念，有助於日後在面對輸出入腳位時，適當的進行電壓減壓或電壓分壓的動作，以免將實驗板的輸出入腳位燒毀

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

## 二、樹莓派GPIO與LED接線

介紹樹莓派的GPIO接腳基本概念，並且利用此概念，配合麵包板把電阻和紅色LED接線，接好後一切就緒，就可以開機進行程式撰寫！ 提醒一下：接線時，最好是在關機狀態，以免把樹莓派搞壞。

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

## 三、用Python點亮LED

Python語言易學易用，只要稍稍學習就可以開始運用它來開發程式，雖然是用「純英文來寫程式」，但稍微練習學幾個單字，就可以逐步上手。

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

```python
import RPi.GPIO as gpio
import time

led = 17

gpio.setmode(gpio.BCM)
gpio.setup(led, gpio.OUT)

try:
    while True:
        gpio.output(led, gpio.HIGH)
        time.sleep(1)
        gpio.output(led, gpio.LOW)
        time.sleep(1)
except KeyboardInterrupt:
    pass

gpio.cleanup()
```

## 四、channel佔用警告修正及gpiozero模組初探

使用Rpi.GPIO，如果程式結束前沒有清除掉使用的channel，會出現警告訊息，雖然沒有問題，但最好還是利用try...except這種例外處理，接受鍵盤中斷訊息(Ctrl + C)，然後手動清除使用的資料。 除此之外，還有一個更方便好用的gpiozero模組，利用它僅使用一行指令就可以讓LED閃爍。

gpiozero官網：[https://gpiozero.readthedocs.io/en/st...](https://www.youtube.com/redirect?redir_token=oKdpEk5fdpQMGuJXmKgRCHM_1Rx8MTU1MjYzMTc2MUAxNTUyNTQ1MzYx\&q=https%3A%2F%2Fgpiozero.readthedocs.io%2Fen%2Fstable%2F\&event=video_description\&v=mUlVgjrG8gQ)

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


---

# 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://s761111.gitbook.io/raspi-sensor/yong-python-liang-led.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.
