Author Topic: Controller Button presses - the logic behind only doing things once.  (Read 868 times)

Louis L

  • Administrator
  • Hero Member
  • *****
  • Posts: 567
For languages like LabVIEW where we have to process all inputs every x milliseconds (say 10 ms), a user who holds a button down can cause an action to repeat itself. This kind of button action is ok in some circumstances. For example supposed you want to activate a motor as long as the button is held down.

But what about the situation where you want an action to take place and the button is just a "click" - press and release? If the button is held down for more than one pass of the 10 ms, the software will register more than one instance of the command. Depending on how much time it takes to complete the command, you can get into some serious problems here.

The answer is to not just look at the button press but also the preceding state of that button. You need to save some state. For the case of a single button, there are 2 inputs in our function - the previous state and the current state. Each represents a button press. There are therefore 4 possibilities. '0' means not pressed, '1' means pressed.

Previous  Current
   0            0         <== nothing to do
   0            1         <== button was just pressed. Go do something
   1            0         <== button was released, do nothing
   1            1         <== button is still held, ignore it.

So you see that there is only one state pair where we actually something. Make sure you assign a new "previous" state on each pass of the code!

Pseudo-code below:

BOOL PreviousButtonState = FALSE;     // Global variable or class member, initialized.

// class or button processing function
BOOL NewButtonState = GetButton();  // make call to get a button to check it's state
if ( (! PreviousButtonState) && (NewButtonState) )
   ProcessButton;                                  // this is a newly pressed button so go do something.
PreviousButtonState = NewButtoState;   // Always update the previous button state
« Last Edit: January 30, 2018, 10:08:35 AM by Louis L »