HOME

LEDs - 06

NEXT: LEDs 07

In this section we are going to:

- "Bit Manip: OR with 1 to set, AND with 0 to clear."

- Use Bit Manip to only change bit 7 of PBOUT

- Learn and apply a few bit manipulation shortcuts to simplify coding

Bit Manip

When we used PBOUT = 0x80, we thought we were manipulating only bit 7 (7654 3210). In actuality, we were changing whatever the states of all of the bits were to the new values, 1000 0000.

According to section 5 that we just reviewed, we know if we OR a bit with a 1, we will set that bit to a 1. If we OR the other bits with 0, then whatever they were will not change: a 0 stays a 0 and a 1 stays a 1.

 

An OR Example

If we wish to change PBOUT so that only bit 7 is changed, we could use:

PBOUT = PBOUT | 0x80.  PBOUT will take on the new value of the command.

 

Let's say we start with a source value of 0x55 for PBOUT for example. In binary that's 0101 0101.

The binary value for mask 0x80 is 1000 0000.

If we OR the source value 0x55 with mask 0x80, then in binary the process would look like this:

0101 0101  (0x55) Source

1000 0000  (0x80) Mask

-------------- OR

1101 0101  (0xD5) Result of OR process

 

Applying OR masking of PB7 to enable High-Drive current means selecting PBADDR first, then PBCTL next:

PBADDR = 4;                  // High-drive enabled.

PBCTL = PBCTL | 0x80   // Pin PB7 selected (1000 0000) for high-drive current.

 

There is a C Shortcut for bit manip of OR

In C there is a bit manip shortcut for PBCTL = PBCTL | 0x80: it's PBCTL |= 0x80.

So the command pair are now:

PBADDR = 4;

PBCTL |= 0x80,

 

An AND Example

If we wish to change the direction of just PB7 to an output, we would want the bit to become a 0, that is it needs to be cleared, but we don't want to change any of the other bits. If we AND a 0 with a 1, it remains a 0. If we AND a 1 with a 1, it remains a 1. So to clear any particular bit, only that bit will be ANDed with a 0 and all of the other bits will be ANDed with 1.

PBADDR = 1;                    // Data direction selected.

PBCTL = PBCTL & 0x7F;   // Pin PB7 selected (1000 0000) to be ANDed with mask 0x7F (0111 1111).

 

There is a C Shortcut for bit manip of AND

Yes, it's the same shortcut used for OR:

PBADDR = 1;

PBCTL &= 0x7F;

 

An even better C shortcut for bit manip of AND

At first glance it is not obvious we have cleared just PB7. We're going to use the NOT operator represented with the symbol "~" to make the code easier to read.

If we NOT the 8 bits of 0x80, 1000 0000, they become 0xEF, 0111 1111. This what we need to retain the original mask of 0x80. Here is the new code that uses the NOT symbol, "~", to invert the mask of 0xEF to 0x80.

PBADDR = 1;          // Data direction selected.

PBCTL &= ~0x80;   // Clear bit 7 so a 0 is used to select output direction for PB7.

 

And here is the final code for just port B:

NEXT: LEDs 07

TOP

 

HOME