EE 308
Setting and Clearing Bits
using Assembly and C
- To put a specific number into a memory location or register (e.g.,
to put 0x55 into PORTA):
- In assembly:
ldaa #$55
staa PORTA
- In C:
PORTA = 0x55;
- To set a particular bit of a register (e.g., set Bit 4 of PORTA) while
leaving the other bits unchanged:
- In assembly, use the bset instruction with a mask which has 1's
in the bits you want to set:
bset PORTA,#$10
- In C, do a bitwise OR of the register with a mask which has 1's in
the bits you want to set:
PORTA = PORTA | 0x10;
or
PORTA |= 0x10;
- To clear a particular bit of a register (e.g., clear Bits 0 and 5 of PORTA)
while leaving the other bits unchanged:
- In assembly, use the blcr instruction with a mask that has
1's in the bits you want to clear:
bclr PORTA,#$21
- In C, do a bitwise AND of the register with a mask that has 0's in
the bits you want to clear:
PORTA = PORTA & 0xDE;
or
PORTA = PORTA & ~0x21;
or
PORTA &= ~0x21;
Bill Rison
2001-02-12