slehmann36 slehmann36 - 3 months ago 14
C Question

Run Code Once per Button Press - Arduino

I am stuck trying to get certain pieces of code code to run only once per button press (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;
}
}


The above code uses the box-standard Lamp Timer example that comes with the MsTimer2 and EventFuse libraries.

In the loop section there are some while loops which seam to be infinite loops. All I need is a war to run the code you see inside the while loops only once. Any ideas?

Any help would be much appreciated!

Thanks

Answer

A simple implementation using some flags:

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