【问题标题】:Run Code Once per Button Press - Arduino每次按下按钮运行一次代码 - Arduino
【发布时间】:2016-02-09 16:18:30
【问题描述】:

我一直试图让某些代码代码在每次按下按钮时只运行一次 (digitalRead)。

void setup() {
    // Set up and init all outputs to off
    pinMode(2, INPUT);
    pinMode(7, INPUT);

    Serial.begin(9600);
    while (!Serial);
    Serial.println("Test");

    for(byte i = 0; i<OutputCount; i++){
        pinMode( outputs[i][OutputPin], OUTPUT);
        digitalWrite( outputs[i][OutputPin], LOW );

        // Set up an event fuse for this output.
        eventFuse.newFuse( i, outputs[i][OffTime], INF_REPEAT, OutputHandler );
    }

    // Set MsTimer2 for one second per tick.
    MsTimer2::set(100, timerTick );
    MsTimer2::start();
}

void loop(){
    if (digitalRead(2) == HIGH) {
        while (i < 1){
            switchPos = 2;
            MsTimer2::start();
            i++;
        }
    }
    else if (digitalRead(7) == HIGH) {
        while (i < 1){
            switchPos = 7;
            MsTimer2::stop();
        }
    }
    else {
        switchPos = 0;
        i = 0;
    }
}

上述代码使用了 MsTimer2 和 EventFuse 库附带的 box-standard Lamp Timer 示例。

在循环部分有一些 while 循环,它们接缝为无限循环。我所需要的只是一场战争,让你在 while 循环中看到的代码只运行一次。有什么想法吗?

任何帮助将不胜感激!

谢谢

【问题讨论】:

  • 你想用你的循环实现什么?你有一个单次迭代循环(即没有其他目的),一个总是无限循环。另外,你在哪里定义 i?
  • 你可能在loop() 中忘记了第二个i++ 中的while

标签: c loops while-loop arduino


【解决方案1】:

使用一些标志的简单实现:

int twoFlag, sevenFlag;

void loop(){
    if (digitalRead(2) == HIGH) {
        if (!twoFlag) {
            switchPos = 2;
            MsTimer2::start();
            delay(10); // to avoid errors from chattering or bouncing
            twoFlag = 1;
        }
    } else {
        twoFlag = 0;
    }
    if (digitalRead(7) == HIGH) {
        if (!sevenFlag) {
            switchPos = 7;
            MsTimer2::stop();
            delay(10); // to avoid errors from chattering or bouncing
            sevenFlag = 1;
        }
    } else {
        sevenFlag = 0;
    }
}

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2015-06-25
    相关资源
    最近更新 更多