8 years, 4 months ago.

push and hold button?

Hi,

Has anyone had any luck designing a push and hold button before? For example, pushing a button for less than 2 seconds does one thing but holding it for longer does something else..

I've been playing around with { Timer t; t.start() t.stop() } but it's a bit hit and miss so far. Also, once called, I cannot get timer to clear or reset to test the same thing again.

Any thoughts much appreciated.

1 Answer

8 years, 4 months ago.

hi Tom,

if you simply poll the signal, it might look something like this (caution: I did not compile this):

DigitalIn pbutton(p21);
Timer t;
int timeAtPress;

main() {
    t.start();
    bool pressed = false;

    while (1) {
        if (pbutton) {         // maybe if (!pbuttton) { if your signal is inverted.
            pressed = true;
            if (t.read() - timeAtPress < 2) {
                printf("held < 2 s\r\n");
            } else {
                printf("held > 2 s\r\n");
            }
        } else {
            if (pressed) {
                pressed = false;
                if (t.read() - timeAtPress < 2) {
                    printf("released < 2 s\r\n");
                } else {
                    printf("released > 2 s\r\n");
                }
            }
            timeAtPress = t.read();    // keep resetting the start time when not held
        }
    }
}

Accepted Answer