问题
As mentioned in the question , I was wondering whether it is possible for the controller to detect two button press simultaneously.
I am new to controller programming and started with the basics - blinking LED, then moved to buttons and now trying to play around button presses. I wanted to set some flag when both buttons are pressed together .
But as of I know, Only one ISR will be called in this case, thus detecting a single press. How can we achieve this...
(In some electronic devices, it has a specific functionality when we press certain buttons together e.g. resetting a phone when one presses 3 appropriate buttons simultaneously)
regards, Messi
回答1:
One single ISR triggered is not sufficient to detect a single button press. Because of the electro-mechanical signal bounce you get from all buttons, you need some kind of de-bouncing algorithm.
Furthermore, you need the program to be immune to EMI so that multiple interrupts won't create havoc on the stack whenever there are lots of pulses coming from the button(s).
For example:
If the buttons are connected to different ports that give different interrupts, create one interrupt per button. If they are connected to the same port, they can usually trigger the same interrupt (depending on MCU).
Whenever you get an interrupt as result of any signal edge (raising or falling) from the button, then in the ISR disable the interrupt and start a hardware timer of typically 5-10ms depending on the button. The timer should preferably trigger a timer interrupt.
Disabling the interrupt is necessary to filter out spurious interrupts caused by the bouncing and by potential EMI glitches.
The timer is necessary for the de-bouncing. If you cannot find the exact signal bounce time in the button data sheet (you most often don't), then simply measure it using an oscilloscope.
When the timer elapses, read the port and store the result in a variable. Enable the button interrupt once again.
The variable needs to be declared at file scope as
static volatile
. Static for private encapsulation, which is needed for good program design. Volatile to prevent against common compiler optimizer bugs, where the compiler doesn't realize that a variable has been modified by an ISR.Implement the same for the first button. You'll have two different variables telling the current state of the buttons. Simply compare these two variables with each other to tell whether or not two buttons are pressed at the same time.
来源:https://stackoverflow.com/questions/23557921/how-to-detect-two-or-more-button-press-gpio-at-the-same-time-by-a-microprocess