24. A PBASIC like "Button" Debounce Macro
Here is a Macro that works similarly to the Parallax Basic Stamp's
"Button" Function:
Button macro Port, Pin, Down, Delay, Rate, Variable, Target, Address
local ButtonEnd
incf Variable, w ; Increment the Counter Variable
if ((Down == 0) && (Target == 0)) || ((Down == 1) && (Target == 1))
btfsc Port, Pin ; If Low, then Valid Pin
else
btfss Port, Pin ; If High, then Valid Pin
endif
clrw ; Not Pressed, Clear the Counter
movwf Variable ; Save the Counter Value
movlw Delay & 0x07F
subwf Variable, w ; Button Debounced?
btfsc STATUS, Z
goto Address ; If Equal, then "Yes"
if ((Delay & 0x080) != 0) ; Is Autorepeat used?
btfsc STATUS, C
decf Variable ; No - Decrement if > "Delay"
else
btfss STATUS, C
goto ButtonEnd ; Less than Expected - End
xorlw Rate ; At the Autorepeat Point yet?
btfsc STATUS, Z
goto ButtonEnd ; No - Keep Incrementing
movlw Delay ; Yes, Reset back to the Original
movwf Variable ; Count and Repeat
goto Address
endif
ButtonEnd ; Macro Finished
endm
The parameters are defined as:
Port, Pin - the Button Pin (ie "PORTA, 0").
Down - The State When the Button is Pressed.
Delay - The number of iterations of the Macro code before the
"Address" is jumped to (to 127). If Set to 0, then Jump if
"Target" met without any debouncing. If Bit 7 of "Delay" is
set, then no auto-repeats.
Rate - After the Initial jump to "address", the number of cycles
(to 127) before autorepeating.
Target - The state ("1" or "0") to respond to.
Address - The Address to Jump to when the Button is pressed or
Auto-repeats