Best method to trigger only one event when a button is pressed?

@Falcon
I just tried solving your problem, and I have come up with a solution that solves bouncing and the need for delays.

#include "Particle.h"

/*SYSTEM_THREAD(ENABLED);
SYSTEM_MODE(MANUAL);*/

#define BUTTON D0

bool pressing = false;
unsigned int lastPress, lastRelease, previousLastPress, previousLastRelease;

int buttonHandler()  // 0 = not pressing, 1 = still pressing, 2 = just stopped pressing, 3 = just started pressing
{
        if (digitalRead(BUTTON) == LOW && pressing == false) // 3 = just started pressing
        {
                pressing = true;
                lastPress = millis();
                return 3;
        }

        if (digitalRead(BUTTON) == HIGH && pressing == true) // 2 = just stopped pressing
        {
                pressing = false;
                lastRelease = millis();
                return 2;
        }

        if (pressing == true) // 1 = still pressing
        {
                return 1;
        }
        else // 0 = not pressing
        {
                return 0;
        }
}

void setup() // Put setup code here to run once
{
        pinMode(BUTTON, INPUT_PULLUP);
        digitalWrite(BUTTON, HIGH);
        Serial.begin(9600);
}

void loop() // Put code here to loop forever
{
        int check = buttonHandler(); // get press status

        if (previousLastRelease != lastRelease) // Button bumped, pushed and then released at later time
        {
                // Particle.publish("click","Click took "+String(lastRelease - lastPress)+" ms");

                Serial.println("Click took "+String(lastRelease - lastPress)+" ms");
                previousLastRelease = lastRelease;
        }

}

In this example, the Photon replies via Serial how long a click took.

Example output (from Serial) for a bunch of “normal clicks”:

Click took 84 ms
Click took 91 ms
Click took 133 ms
Click took 131 ms
Click took 123 ms
Click took 119 ms
Click took 116 ms
Click took 129 ms
Click took 128 ms
Click took 134 ms
Click took 136 ms
Click took 1 ms
Click took 145 ms
Click took 148 ms

Sometimes I get values lower than 10ms, which I assume is just noise or bouncing, but it works really well.

2 Likes