We set a specific bit in a register to turn on a feature or control hardware without changing other settings.
0
0
Setting a specific bit in a register in Embedded C
Introduction
Turning on an LED connected to a microcontroller pin.
Enabling a sensor by setting its control bit.
Configuring communication settings by setting bits in a control register.
Activating interrupts by setting the interrupt enable bit.
Changing device modes by setting mode bits in a register.
Syntax
Embedded C
REGISTER |= (1 << BIT_POSITION);REGISTER is the name of the hardware register.
BIT_POSITION is the zero-based position of the bit to set (0 for least significant bit).
Examples
Sets bit 3 of PORTA register to 1, turning on the connected pin.
Embedded C
PORTA |= (1 << 3);
Sets bit 0 of CONTROL_REG to enable a feature.
Embedded C
CONTROL_REG |= (1 << 0);
Sets the highest bit (bit 7) of STATUS register.
Embedded C
STATUS |= (1 << 7);
Sample Program
This program starts with all bits off in registerA. It sets bit 2 to 1 using the bitwise OR and shift. Then it prints the register bits from left to right.
Embedded C
#include <stdio.h> int main() { unsigned char registerA = 0b00000000; // all bits off int bit_to_set = 2; // we want to set bit 2 // Set bit 2 registerA |= (1 << bit_to_set); printf("Register after setting bit %d: 0b", bit_to_set); for (int i = 7; i >= 0; i--) { printf("%d", (registerA >> i) & 1); } printf("\n"); return 0; }
OutputSuccess
Important Notes
Using |= keeps other bits unchanged while setting the chosen bit.
Bit positions start at 0 from the right (least significant bit).
Make sure the register variable is wide enough to hold the bits you want to set.
Summary
Use REGISTER |= (1 << BIT_POSITION); to set a specific bit.
This changes only the chosen bit without affecting others.
Bit positions count from 0 at the rightmost bit.