程式碼:
const int buttonPin = 2; // 按鈕接腳
const int ledPin = 13; // LED 接腳 (板子內建 LED)
bool ledState = false; // LED 閃爍狀態
bool buttonState = false; // 當前按鈕狀態
bool lastButtonState = false; // 上次按鈕狀態
unsigned long previousMillis = 0;
const long interval = 500; // 閃爍間隔 (毫秒)
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // 使用內建上拉電阻
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
// 偵測按鈕由高到低的跳變(按下去)
if (lastButtonState == HIGH && buttonState == LOW) {
ledState = !ledState; // 切換閃爍狀態
}
lastButtonState = buttonState;
if (ledState) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
digitalWrite(ledPin, !digitalRead(ledPin)); // 反轉 LED 狀態
}
} else {
digitalWrite(ledPin, LOW); // 關閉 LED
}
}
測試影片網址:https://www.youtube.com/shorts/8vwdBG2wEsA
限會員,要發表迴響,請先登入