按鈕控制LED-micropython

 按鈕控制LED--micropython

接線




from machine import Pin
from time import sleep

led = Pin(2Pin.OUT)
button = Pin(4Pin.IN)

while True:
    led.value(button.value())
    sleep(0.5)


首先從machine載入Pin,從time載入sleep

from machine import Pin from time import sleep

下面跨號有兩個參數,5是esp32上的GPIO接腳,Pin.OUT表示第5腳位預設為輸出

led = Pin(5, Pin.OUT)

和上面一樣道理,只不過第二個參數是用Pin.IN表示按鈕是以輸入的方式設定

button = Pin(4, Pin.IN)


當我們按下按鈕時,button.value() 返回 1。因此,這與 led.value(1) 相同。這會將 LED 狀態設置為 1,點亮 LED。當按鈕未被按下時,button.value() 返回 0。因此,我們有 led.value(0),並且 LED 保持關閉狀態。

led.value(button.value())



實作結果









留言

這個網誌中的熱門文章

使用PWM控制伺服馬達-micropython

DHT11+OLED+IFTTT+LINE-notity-micropython

BMP280氣壓,溫度模組-micropython