Proc keydetect() '16ms or greater is considered debounce time. a person can click and release in about 32 ms. This routine must iterate at least once per 16mS!
'8 channels (bits) @ 1 switch per bit simultaneously processed. Debounced Short press (16 to 512mS) and Long press (>512mS sec)detection
'Both press and release actions are debounced.
'requires a 8mS counter 'dbouncecount', preferably interrupt driven.
'dbkeystate' = closed debounced switches. 'holdkeystate' = closed 'long press' switches. 'keytrans' and 'holdtrans' track the respective switch transitions (both press & release)
'keytrans' and 'holdtrans' (reset every iteration) are useful when ensuring that a single key press is not repetitively detected as a fresh press during its duration (of multiple detection iterations).
Dim temp As Byte
swstate = 0
keytrans = 0
holdtrans = 0 'reset states
Call mapswitches() 'assign switches to swstate bits.
temp = swstate Xor lastkeystate 'check for any changes in sw states.
lastkeystate = swstate 'make old state = new
If temp <> 0 Then dbouncecount = 0 'reset counter if no switch detected, else permit dbounce count.
If dbouncecount.1 Then '@ an increment of 1 per 8mS, debounce.1 tests 16ms or greater.
keytrans = lastkeystate Xor dbkeystate 'keytrans bits monitors the switches that have changed state 'short press' after debounce.
dbkeystate = keytrans Xor dbkeystate 'update debounced byte with current switch (now debounced) states
Endif
'evaluate dbouncestate to determine which keys have been released
temp = dbkeystate And holdkeystate
holdtrans = temp Xor holdkeystate 'update long press (hold) transition byte.
keytrans = holdtrans Xor keytrans 'clear matching 'short press' debounced transitions, a 'long press' key is different to a 'short press' key
holdkeystate = holdtrans Xor holdkeystate 'toggle long press' keystate to on or off based on its old state & new transition.
temp = dbkeystate Xor holdtrans
If temp = 0 Then Goto done
If dbouncecount.6 = 0 Then Goto done '512msec not elapsed
temp = dbkeystate Xor holdkeystate 'state changes
holdtrans = temp Or holdtrans 'longpress transitions
holdkeystate = temp Xor holdkeystate 'apply changes.
done:
End Proc
Proc mapswitches() 'assign swstate bits to matching switch inputs. Organises switches scattered among input port pins or in an analog volt ladder.
TRISB.3 = 1
ANSELH.1 = 1
Adcin 9, tactile 'sample switch resistance ladder V.
tactile = 145 - tactile
Select Case tactile 'assign a swich based on the voltage detected.
Case < 5
swstate.0 = 1 'sw 0 closed
Case < 10
swstate.1 = 1 'sw 1 closed
Case < 15
swstate.2 = 1 'sw 2 closed
Case < 20
swstate.3 = 1 'sw 3 closed
Case Else
EndSelect
TRISB.3 = 0
ANSELH.1 = 0
End Proc