Contents ...
udn網路城邦
Arduino 按鈕控制LED閃爍
2025/08/29 09:21
瀏覽21
迴響0
推薦0
引用0

程式碼:

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

全站分類:興趣嗜好 其他
自訂分類:Arduino
上一則: arduino 按鈕控制led燈4種變化
下一則: 按鈕控制跑馬燈方向

限會員,要發表迴響,請先登入