0
0
Embedded Cprogramming~5 mins

OR for setting bits in Embedded C

Choose your learning style9 modes available
Introduction

We use OR to turn on specific bits in a number without changing the other bits.

Turning on a light in a group of lights controlled by bits.
Enabling specific features in a device by setting bits.
Marking options as active in a settings byte.
Setting flags in a status register without losing current flags.
Syntax
Embedded C
variable = variable | mask;

variable is the number where bits will be set.

mask has 1s in the bit positions you want to turn on.

Examples
Set the first bit of flags to 1.
Embedded C
flags = flags | 0x01;
Turn on the third bit of status.
Embedded C
status = status | 0x04;
Shortcut to set the fifth bit of control.
Embedded C
control |= 0x10;
Sample Program

This program starts with all bits off in flags. Then it sets bits 0 and 2 using OR with mask. The result shows which bits are now on.

Embedded C
#include <stdio.h>

int main() {
    unsigned char flags = 0x00;  // all bits off
    unsigned char mask = 0x05;   // bits 0 and 2 set (00000101)

    // Set bits in flags using OR
    flags = flags | mask;

    printf("Flags after setting bits: 0x%02X\n", flags);
    return 0;
}
OutputSuccess
Important Notes

Using OR to set bits never turns any bit off.

The mask should have 1s only where you want to set bits.

Use hexadecimal (like 0x01, 0x04) to easily see which bits you are setting.

Summary

OR operation sets bits to 1 without changing others.

Use a mask with 1s in the bit positions you want to set.

Shortcut: variable |= mask; does the same as variable = variable | mask;.