Consecutive bit assignments in the same register

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Consecutive bit assignments in the same register

394 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by Mohannad on Tue Mar 31 03:42:54 MST 2015
Hello,

I'm having a problem regarding assigning bit consecutively in the same register on LPC1769.

For example, to display number 5 on 7 segment display I write this statement and it works perfectly:


Quote:
LPC_GPIO0->FIOPIN = ~(1<<16 | 1<<17 | 1<<7 | 1<<1 | 1<<18);



However, if I have written consecutive statements to assign the same bits, it doesn't work.


Quote:

LPC_GPIO0->FIOPIN |= ~(1<<16) ;
LPC_GPIO0->FIOPIN |= ~(1<<17) ;
LPC_GPIO0->FIOPIN |= ~(1<<7) ;
LPC_GPIO0->FIOPIN |= ~(1<<1) ;
LPC_GPIO0->FIOPIN |= ~(1<<18) ;



I was just curious, why the consecutive bit assignment doesn't work?!

Your help is appreciated.

Thank you,
Labels (1)
0 Kudos
2 Replies

388 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by nerd herd on Tue Mar 31 07:26:00 MST 2015
Hi Mohannad,

OldManVimes gave a clear proof of why your two bit assignments are not the same. In case you were interested in delving deeper, the formal reason why the two bit assignments are not equal is due to De Morgan's Law. Essentially, when you NOT a statement such as ~(1 << 16 | 1 << 17), the NOT will flip the OR into a AND, making the equivalent statement of ~(1 << 16) & ~(1 << 17). For more information:

http://en.wikipedia.org/wiki/De_Morgan%27s_laws

0 Kudos

388 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by OldManVimes on Tue Mar 31 04:16:32 MST 2015
Boolean logic, that's why.

Simpler example in binary where integers are 3 bits wide.

0b001
0b010
0b100
-------- | (i.e OR them together)
0b111

Take 3 values (1, 2 and 4) and OR them. Result: 7
Now take the inverse of 7: ~0b111 = 0b000

Next section:
FIOPIN |= ~0b001 is equal to FIOPIN |= 0b110
FIOPIN |= ~0b010 is equal to FIOPIN |= 0b101
FIOPIN |= ~0b100 is equal to FIOPIN |= 0b011
After these 3 operations, what is the value of FIOPIN (assuming that the start value was zero)?

FIOPIN = 0;
FIOPIN |= 0b110;
FIOPIN |= 0b101;
FIOPIN |= 0b011;
Result: FIOPIN = 0b111;

So because of the change in behavior, the value of FIOPIN is the inverse of what you expected. In conclusion: the two pieces of code do not apply the same operation. You can make it right though.

FIOPIN = 0b111;
FIOPIN &= ~0b001; // Set bit 0 to 0, leave the rest unchanged
FIOPIN &= ~0b100; // Set bit 2 to 0, leave the rest unchanged
Result: FIOPIN = 0b010; // Great.

Hope this helps,
Vimes
0 Kudos