Arduino問題 請高手解答 急?

#include <TimedAction.h>

const int ledPin = 11;

const int ledPin2 = 13;

int button = 2;

int ledState = LOW, ledState2 = LOW; //存放LED開或關的狀態

int buttonState=0; //存放按鈕的狀態

long interval = 1000;

long interval2 = 500;

int old_buttonState = 0; // 存放按鈕上一次的狀態

void blink();

void print();

TimedAction blinkAction = TimedAction(interval,blink);

TimedAction printAction = TimedAction(interval2,print);

void setup()

{

pinMode(ledPin,OUTPUT);

pinMode(ledPin2,OUTPUT);

pinMode(button,INPUT);

}

void loop()

{

blinkAction.check();

printAction.check();

}

void blink()

{

if(ledState == LOW)

ledState = HIGH;

else

ledState = LOW;

digitalWrite(ledPin,ledState);

}

void print()

{

if(ledState2 == LOW)

ledState2 = HIGH;

else

ledState2 = LOW;

digitalWrite(ledPin2,ledState2);

}

請問裡面有兩個活動1個LED每一秒閃一次,另一個LED每0.5秒閃一次,我現在要在裡面加按鈕,按下去要交換活動,請問如何加在裡面 謝謝

已更新項目:

是的交換閃爍的週期!

1 個解答

評分
  • 3 年前
    最佳解答

    交換活動是指交換閃爍的週期嗎?

    不知道你電路是如何接的 先幫你設按鈕上緣觸發中斷

    #include <TimedAction.h>

    const int ledPin = 11;

    const int ledPin2 = 13;

    int button = 2;

    int ledState = LOW, ledState2 = LOW; //存放LED開或關的狀態

    int buttonState=0; //存放按鈕的狀態

    long interval = 1000;

    long interval2 = 500;

    int old_buttonState = 0; // 存放按鈕上一次的狀態

    void blink();

    void print();

    TimedAction blinkAction = TimedAction(interval,blink);

    TimedAction printAction = TimedAction(interval2,print);

    /*add*/boolean flag_btn = false; //按鈕狀態

    void setup()

    {

    pinMode(ledPin,OUTPUT);

    pinMode(ledPin2,OUTPUT);

    //pinMode(button,INPUT);

    /*add*/pinMode(interruptPin, INPUT_PULLUP);

    /*add*/attachInterrupt(digitalPinToInterrupt(interruptPin), click_btn, RISING );//設定按鈕中斷事件(RISING=上緣觸發)

    }

    void loop()

    {

    blinkAction.check();

    printAction.check();

    }

    /*add*/void click_btn() {flag_btn = !flag_btn;}//按鈕中斷事件,用flag_btn記錄

    void blink()

    {

    if(ledState == LOW)

    ledState = HIGH;

    else

    ledState = LOW;

    /*add*/if(!flag_btn) digitalWrite(ledPin,ledState); //根據flag_btn將指定週期設定給不同的LED

    /*add*/else digitalWrite(ledPin2,ledState);

    }

    void print()

    {

    if(ledState2 == LOW)

    ledState2 = HIGH;

    else

    ledState2 = LOW;

    /*add*/if(!flag_btn) digitalWrite(ledPin2,ledState2); //根據flag_btn將指定週期設定給不同的LED

    /*add*/else digitalWrite(ledPin,ledState2);

    }

還有問題?馬上發問,尋求解答。