Toggle

cpedw

Senior Member
#1
I just discovered that TOGGLE can only be applied to an output pin. I was using it with a bit variable.

There was no syntax error but neither was it altering the variable.
I can use bit = bit + 1; TOGGLE was more readable.
 

hippy

Technical Support
Staff member
#2
The TOGGLE command does indeed only affect an output pin.

Which output pin depends on the value in the variable used; for a bit variable it will only be 0 or 1, and thus B.0 or B.1 output will be toggling, or C.0 or C.1 if an 8-pin PICAXE.

The variable itself won't be changed. Using "bit = bit ^ 1" is my preference to invert a bit but +1 or -1 works just as well.
 

Technical

Technical Support
Staff member
#3
'toggle bit3' is valid syntax, but won't do what you want.

If bit3 is currently high, it will 'toggle 1' and if low it will 'toggle 0'. So output pin B.1 or B.0 would change!
 

cpedw

Senior Member
#4
'toggle bit3' is valid syntax, but won't do what you want.

If bit3 is currently high, it will 'toggle 1' and if low it will 'toggle 0'. So output pin B.1 or B.0 would change!
I just reread this carefully. Does it mean that TOGGLE can be used for indirect addressing of output ports?
 

hippy

Technical Support
Staff member
#5
I just reread this carefully. Does it mean that TOGGLE can be used for indirect addressing of output ports?
Yes, you can toggle a physical pin which is identified by a pin value within a variable. For example to effect a "TOGGLE C.3" ...

Code:
  b1 = C.3
  Toggle b1
To set all pins of Port B high ...

Code:
For b1 = B.0 To B.7
  High b1
Next
 

Flenser

Senior Member
#6
What about using the NOT command to toggle a bit?
Code:
bit0 = NOT bit0
No matter what command you decide to use you can define a macro to get the style of readable code you describe:
Code:
#MACRO ToggleBit(parm)
  parm = NOT parm
#ENDMACRO

ToggleBit(bit0)
For the X2 chips you can also consider the INV command.
As pointed out in <PICAXE Program size Optimisation and Speed - Rev D.pdf> the X2 INV uses less code space than NOT but I don't know whether it is any faster.
 

hippy

Technical Support
Staff member
#7
For the X2 chips you can also consider the INV command.
As pointed out in <PICAXE Program size Optimisation and Speed - Rev D.pdf> the X2 INV uses less code space than NOT but I don't know whether it is any faster.
It varies a little because of code alignment, and one never knows how code is aligned, but usually the less memory used the faster it will execute as the interpreter has less to read before acting upon what it has read.

The most efficient bit inversion is possibly "bitX = bitX ^ 1".

The advantage of hiding things in #MACRO, beyond the main code being how one would like it, is that all the possibilities can be tried and tested, and, even if an option one doesn't particularly understand or like aesthetically turns out to be best, that will only ever appear in one place.
 
Top