PIC: 16F How to toggle a single bit in file register

Status
Not open for further replies.

eblc1388

Active Member
Hi guys,

On a 16F877, I have set up eight flags using a single register called "flags" and I need to change them or toggle them individually.

I know I can test the bit and change it, but is there an easy way to just toggle a single bit, for example?
 

It's VERY, VERY simple - you should read the datasheet, there's only 35 instructions!.

But see BSF (to set a bit), and BCF (to clear a bit).
 
Thanks Nigel, but I like to "toggle" the bit not set or clear it.

Nevermind, I figured it out myself.

Code:
movlw    B'00001000' ;toggle bit3
xorwf    flags,F
 
eblc1388 said:
Thanks Nigel, but I like to "toggle" the bit not set or clear it.

Nevermind, I figured it out myself.

Code:
movlw    B'00001000' ;toggle bit3
xorwf    flags,F

Exactly 8)

And a little optimization trick : say you frequently toggle 2 or multiple flags at the same time, you can OR them together as assembler #defines and use the #defined value to toggle both flags in 1 instruction

Code:
#define		FLAG1		B'00000001'
#define		FLAG2		B'00000010'
#define		FLAGS1n2   FLAG1 | FLAG2

[...]

	movlw	FLAGS1n2
	xorwf	[file]

Very useful for some algorithms... Sorry if I'm being Captain Obvious here :lol:
 
Jay.slovak said:
on PIC18F, you would just use BTG (Bit togle) instruction

Yes, but as you can see from my previous example, xorwf is more "powerful". If I am not mistaken, BTG limits you to 1 bit at a time?...
 
Actually yes, good point here (I didn't think about that).
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…