how do I program a flipflop button?

50buzz

New Member
Hi, I am new to picaxes and am really enjoying the amazing flexibility they offer, but I am struggling with basic. I want to turn an output on and latch it with a single push of a momentary button. A second push should unlatch it. A bit like the caps lock on a keyboard. The hardware is no problem - its just writing the code in basic that I am stuck on. Thanks.
 

Gavinn

Member
Hi,

The command would be TOGGLE, it changes an output to 1 if 0 and 0 if 1. A simple bit of code would be...

Code:
Start:

if pin 1 = 1 then
toggle pin 1
pause 200         'delay to save using command BUTTON for debounce
else
endif

Goto Start
Note although pin 1 is used twice they are different as one is an input pin and the other is an output pin.
 
Last edited:

womai

Senior Member
The code above will malfunction (produce repeated actions) if you keep the button pressed for too long, and on the other hand it will block program execution unnecessarily long if you release the button right away (and will miss repeated button presses during that time). A better approach is:
  1. wait until input goes high
  2. wait a short time and see if it is still high (that wait acts as debounce); about 20 msec is a good choice for typical switches.
  3. do whatever you want to do when the button gets pressen, in this case, toggle the output
  4. wait until the input goes low again
  5. again wait a short time (e.g. 20 msec) before you continue
  6. got back to 1.
I'm intentionally not posting the Basic code for above algorithm, I think it's more fun for you to work on that yourself. But if you get stuck, don't hesitate to ask for help.

Wolfgang
 

BCJKiwi

Senior Member
Recently implemented a subroutine which was labeled PushPush as it converted a momentary PB into a Push on Push off type action.

PB = 1 enters gosub
PushPush:
Variable changed from 0 to 1 , or 1 to 0 achieving the toggle effect
Do while PB = 1 :loop 'stay in loop until PB released debounce and button can be held as long as you like
return.

@Womai - tried not to spill all the beans!
 
Top