Maximite 2: How to make switch trigger only once when pressed


Author Message
TassyJim

Guru

Joined: 07/08/2011
Location: Australia
Posts: 6546
Posted: 08:01pm 30 Nov 2020      

Does not qualify for "sleakest way" but it might be a start for you
Use any digital pin and switch pulls input to ground. Internal pullup should be adequate but you could use external resistor to 3.3V instead.

A capacitor is always advisable although the debounce timer should stop bounce triggers. The capacitor will reduce the number of calls to the sub.

It assumes that you don't reset the timer anywhere in your program.

 OPTION EXPLICIT
 OPTION DEFAULT NONE
 CONST sw_pin = 10
 const debounce = 200
 DIM INTEGER sw_action
 
 SETPIN sw_pin, INTB, clicked, PULLUP
 
 DO
   IF sw_action = 1 THEN
     PRINT "clicked"
     sw_action = 0 ' reset the flag
   ENDIF
   
 LOOP
 
SUB clicked
 STATIC INTEGER old_sw_state, old_time
 LOCAL INTEGER sw_state, new_time, interval
 sw_state = PIN(sw_pin)
 new_time = TIMER
 interval = new_time - old_time
 print "*" ' debug info to show contact bounces
 IF sw_state <> old_sw_state AND interval > debounce THEN
   old_sw_state = sw_state
   old_time = new_time
   IF sw_state = 0 THEN sw_action = 1 ' only set the flag with switch low
 ENDIF
END SUB


(I am one of the lucky ones, it's my left hand that's no use)

Jim