Operators
Lesson 57: Using | Bitwise OR Operator
Learn how bitwise OR combines bits, sets flags, and builds masks for low-level ESP32/Arduino control.
Progress indicator
Lesson 57 of 57
Learning Objectives
- Understand what bitwise OR (|) does at the bit level.
- Use | to set bits in flags and masks.
- Read the bitwise truth table and predict results.
- Understand | vs || and avoid mixing them.
- Apply bit masks in practical Arduino code.
Concept Explanation
What is the Bitwise OR Operator (|)
The | operator compares bits of two numbers position by position.
If either bit is 1, the result bit becomes 1. Only 0|0 gives 0.
Bitwise OR Syntax
result = valueA | valueB;
flags = flags | FLAG_LED_ENABLE;How | Works
- Convert both values into binary bits.
- Compare each bit column (left and right).
- Output 1 if at least one bit is 1.
- Combine all output bits into final number.
Bitwise Truth Table
| A | B | A | B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
Using | with Bit Masks
Bit masks let you store multiple ON/OFF options inside one variable called flags.
flags = flags | FLAG_LED_ENABLE; // set LED bit
flags = flags | FLAG_LOG_SERIAL; // set log bit| vs || (Comparison)
|works on bits of integer values.||works on boolean conditions in if/else logic.- Use
|for masks,||for decision conditions.
When to Use |
- Setting configuration bits in flags.
- Combining multiple option bits into one value.
- Low-level register-style control patterns.
Example Code
This sketch sets bit flags using | and checks flags to control LED and Serial.
const int LED_PIN = 2;
byte flags = 0b00000000;
const byte FLAG_LED_ENABLE = 0b00000001;
const byte FLAG_LOG_SERIAL = 0b00000100;
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
flags = flags | FLAG_LED_ENABLE;
flags = flags | FLAG_LOG_SERIAL;
if (flags & FLAG_LED_ENABLE) {
digitalWrite(LED_PIN, HIGH);
}
if (flags & FLAG_LOG_SERIAL) {
Serial.print("flags = ");
Serial.println(flags, BIN);
}
delay(500);
}Example Code Explanation
flagsstarts at all zero bits.flags = flags | FLAG_LED_ENABLEsets LED enable bit to 1.flags = flags | FLAG_LOG_SERIALsets serial logging bit to 1.- Bit checks decide if LED output and Serial printing should run.
- Serial prints flags in binary for clear visualization.
What Happens Inside
- CPU loads both integer operands.
- Per-bit OR operation runs across all bits.
- Result bits are merged into one output integer.
- Output integer is written back to the target variable.
Common Mistakes with |
- Using
||where bitwise|was needed. - Using decimal masks without checking actual bit pattern.
- Assuming
|clears bits (it only sets bits to 1 where needed).
Best Practices for |
- Define named masks like
FLAG_LED_ENABLEfor readability. - Use binary literals to make bit intent clear.
- Print values in binary while debugging bit operations.
Try it now
Open the simulator workspace and inspect how bit flags change with bitwise OR.