c - 每次按下按钮运行一次代码 - Arduino

标签 c loops while-loop arduino

我一直试图让某些代码片段在每次按下按钮时只运行一次(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 库附带的盒装标准 Lamp Timer 示例。

在循环部分有一些 while 循环,它们看起来像是无限循环。我所需要的只是一场 war 来运行您在 while 循环中看到的代码一次。有什么想法吗?

任何帮助将不胜感激!

谢谢

最佳答案

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

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;
    }
}

关于c - 每次按下按钮运行一次代码 - Arduino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33602020/

相关文章:

将 char * 转换为 char * const *

php - 如何使用 PHP 和 SQL 数据库来更改 HTML <h> 内容?

algorithm - 使用循环对数据进行分组(MATLAB 中的信号处理)

c - 输入文本文件时文件无法正确输出

c - 理解 GCC 依赖 pragma 指令

c - stdio.h 文件错误?

javascript - 为什么我的解决方案有效而其他解决方案无效?

Java 扫描器循环?

java - 即使其中一个条件为真,为什么这个 boolean 值输出为假?

java - 递增多个嵌套 While 循环