Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 10 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
9 years, 10 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
        }
    }
}
