# What is the optimal 'toggle' effect ?

June 4 2011 at 8:49 AM

Situation: A light switch can either be ON or OFF.
If 'ON' = 1 and 'OFF' = 0, what is the optimal way to program a 'toggle' effect?

so: if I start with '0' and hit the spacebar, my '0' becomes '1'.
if I hit the spacebar again, my '1' goes back to being '0'. And so on.

The following is a working program that demonstrates the idea, but it's not optimal. The challenge is to optimize & simplify the program for the same output.

' ======================= ONLY an EXAMPLE not an ENTRY ============

counter% = 0
toggle% = 1

WHILE k\$ <> CHR\$(27)

k\$ = INKEY\$
IF k\$ = CHR\$(32) THEN
counter% = counter% + 1
IF counter% / 2 = counter% \ 2 THEN toggle% = 0 ELSE toggle% = 1
PRINT toggle%
END IF

WEND

 Respond to this message
lawgin

# counter% not needed

June 4 2011, 10:43 AM
 WHILE k\$ <> CHR\$(27) IF INKEY\$ = CHR\$(32) THEN toggle% = ABS(toggle% - 1) PRINT toggle% END IF WEND
 Respond to this message

Moderator

# 1 - toggle%

June 5 2011, 4:42 PM
 eliminates the ABS(). As ChronoKitsune showed, XOR is great for toggling specific individuals bits. If, instead, you want to toggle all the bits (for example: 0 to -1 to 0), you could use NOT. Regards, Michael
 Respond to this message