-->
Page 1 of 2

Best way to toggle a flag 0 to 1 and back

PostPosted: Thu May 18, 2017 9:55 pm
by heckler
Hey group,
I would like to toggle a flag on a button push.
Code: Select allbtn = io(pi,3)
if btn = 0 then
  if flag = 0 then flag = 1
else
  if flag = 1 then flag = 0
endif


is there a better / simpler way??

thanks in advance
dwight

Re: Best way to toggle a flag 0 to 1 and back

PostPosted: Fri May 19, 2017 12:07 am
by jimg
flag=flag xor 1

Re: Best way to toggle a flag 0 to 1 and back

PostPosted: Sat May 20, 2017 3:12 am
by Luc Volders
From lightyears ago.
We always used to use the NOT function.
so toggle = ! toggle

Code: Select alltoggle = 1
button "switch", [switch]
wait

[switch]
toggle = ! toggle
io(po,d2,(abs(toggle))
wait


Toggle wil avry betweem 0 and -1
By using the ABS value of toggle you will be able to set directly an I/O port

Same result as jimg only a bit easier to remember (for me)

Luc

Re: Best way to toggle a flag 0 to 1 and back

PostPosted: Sat May 20, 2017 3:46 am
by Electroguard
If you use an led pin as your flag you can have visual feedback of the state of your flag.
Remember that button interrupt only needs to do something on either the press or release, which is checked in [PRESSED].


Code: Select allledpin = 1     'Use ledpin as your flag variable
buttonpin = 0  'Uses gpio00 flashing button by default, change to suit (needs pullup resistor).
interrupt buttonpin, [PRESSED]
wait

[PRESSED]
if io(laststat,buttonpin) = 0 then gosub [TOGGLE]  'else do nothing
wait

[TOGGLE]
if io(laststat,ledpin) = 1 then io(po,ledpin,0) else io(po,ledpin,1)
return