Set, Clear, Toggle and Check Bit Value in C
In the embedded system design, the system needs to check the input state and then send signals to other devices, or change the state of the outputs. Since each GPIO pin is connected to a different device (some pins are input and other pins may be output or other functions), it is not possible to check the pin state by comparing with a constant value. The setting, clearing, and toggling pins also have the same situation: constant values can not be assigned directly to the port DATA register. Because each GPIO pin is associated with the corresponding bit in the port DATA register, a bitwise operation can be used to solve these issues.
Figure 1: Example of Embedded System
Figure 2: Truth Table for Bitwise-OR
To turn certain bits on, the bitwise-OR operation can be used, following the principle that
n OR 1 = 1 and
n OR 0 = n. Therefore, to make sure a bit is on,
OR can be used with a
1. To leave a bit unchanged,
OR is used with a
Example: Setting 1 on bit 5 and 3, the other bits unchanged.
To light on the lamp which is connected to PB2, bit 2 of the Port B DATA register needs to be set to 1. The following expression shows how to set bit 2 to 1:
PB = PB | _BIT2;
PB |= _BIT2;
Bit Access Functions
The following functions get or set a particular bit of a variable that can make programs easier to read.