- Feb 8, 2001
- 8,968
- 16
- 81
As part of a project I'm working on this summer, I have to connect a momentary switch to a microcontroller. This switch is used as a toggle button to switch between several modes of operation, so if might be pressed several times in somewhat rapid succession.
In any event, I am concerned with writing a good algorithm for this. As of now, the switch is connected to a port with interrupts on-chip and is connected to VDD through a pull-up resistor. The algorithm I have is as follows:
- Interrupt triggered program goes to ISR.
- Disable interrupt
- Sleep 5 ms
- Start timer for 200 ms and continue code
- When timer is up, another ISR clears the interrupt flag and reenables interrupt. At this point the switch can be pressed again.
Now obviously, this means that for this to work correctly the button has to be pressed for less than 200 ms. Otherwise, the bounce when releasing the button triggers the whole thing and two presses are detected rather than one. It also means that the button cannot be pressed twice within a 200ms span because otherwise the second press is not registered.
Is there a better way to do it that is both independent of release time and protects me from bounce when the button is released?
I had thought to change the algorithm to:
- Interrupt triggered program goes to ISR.
- Disable interrupt
- Sleep 5 ms
- Sample the line: if line is low proceed (button currently pressed), proceed with ISR code. if line is high (button is currently released) reenable interrupt and continue code without registering hit.
I would appreciate any input regarding this.
In any event, I am concerned with writing a good algorithm for this. As of now, the switch is connected to a port with interrupts on-chip and is connected to VDD through a pull-up resistor. The algorithm I have is as follows:
- Interrupt triggered program goes to ISR.
- Disable interrupt
- Sleep 5 ms
- Start timer for 200 ms and continue code
- When timer is up, another ISR clears the interrupt flag and reenables interrupt. At this point the switch can be pressed again.
Now obviously, this means that for this to work correctly the button has to be pressed for less than 200 ms. Otherwise, the bounce when releasing the button triggers the whole thing and two presses are detected rather than one. It also means that the button cannot be pressed twice within a 200ms span because otherwise the second press is not registered.
Is there a better way to do it that is both independent of release time and protects me from bounce when the button is released?
I had thought to change the algorithm to:
- Interrupt triggered program goes to ISR.
- Disable interrupt
- Sleep 5 ms
- Sample the line: if line is low proceed (button currently pressed), proceed with ISR code. if line is high (button is currently released) reenable interrupt and continue code without registering hit.
I would appreciate any input regarding this.