Contents ...
udn網路城邦
按鈕控制跑馬燈方向
2025/08/26 15:21
瀏覽155
迴響0
推薦0
引用0

程式碼:

// 定義 LED 引腳

const int ledPins[] = { 3, 4, 5, 6, 7, 8, 9,10};

const int numLeds = 8;

const int buttonPin = 2;  // 使用數位引腳 2 作為中斷引腳 (INT0)

// 變數宣告

volatile int buttonPressCount = 0;  // 記錄按鈕按下次數

int currentLed = 0;                 // 當前點亮的 LED

bool directionRight = true;         // 方向標誌:true 向右,false 向左

void setup() {

  // 初始化 LED 引腳為輸出

  for (int i = 0; i < numLeds; i++) {

    pinMode(ledPins[i], OUTPUT);

  }

  

  // 初始化按鈕引腳為輸入,並啟用內部上拉電阻

  pinMode(buttonPin, INPUT_PULLUP);

  

  // 附加中斷處理函數:當按鈕按下(下降沿)時觸發

  attachInterrupt(digitalPinToInterrupt(buttonPin), buttonPressed, FALLING);

  

  // 初始關閉所有 LED

  for (int i = 0; i < numLeds; i++) {

    digitalWrite(ledPins[i], LOW);

  }

}

void loop() {

  // 根據方向移動 LED

  if (directionRight) {

    moveRight();

  } else {

    moveLeft();

  }

  

  delay(200);  // 控制 LED 移動速度

}

// 中斷處理函數

void buttonPressed() {

  static unsigned long lastInterruptTime = 0;

  unsigned long interruptTime = millis();

  

  // 防彈跳處理:如果兩次中斷間隔小於 200ms,則忽略

  if (interruptTime - lastInterruptTime > 200) {

    buttonPressCount++;  // 增加按鈕按下計數

    

    // 根據奇偶次數決定方向

    if (buttonPressCount % 2 == 1) {

      directionRight = true;  // 奇數次:向右

    } else {

      directionRight = false; // 偶數次:向左

    }

  }

  lastInterruptTime = interruptTime;

}

// 向右移動 LED

void moveRight() {

  // 關閉當前 LED

  digitalWrite(ledPins[currentLed], LOW);

  

  // 移動到下一個 LED

  currentLed++;

  if (currentLed >= numLeds) {

    currentLed = 0;

  }

  

  // 點亮新的 LED

  digitalWrite(ledPins[currentLed], HIGH);

}

// 向左移動 LED

void moveLeft() {

  // 關閉當前 LED

  digitalWrite(ledPins[currentLed], LOW);

  

  // 移動到上一個 LED

  currentLed--;

  if (currentLed < 0) {

    currentLed = numLeds - 1;

  }

  

  // 點亮新的 LED

  digitalWrite(ledPins[currentLed], HIGH);

}

測試影片:

https://youtube.com/shorts/H2pGAO4uKDg?si=-EzgeM3I2F6jtVdh

全站分類:興趣嗜好 其他
自訂分類:Arduino
上一則: Arduino 按鈕控制LED閃爍
下一則: LED右移

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