0
0
Embedded Cprogramming~5 mins

Clearing a specific bit in a register in Embedded C

Choose your learning style9 modes available
Introduction

Sometimes you want to turn off a single switch inside a group of switches without changing the others. Clearing a specific bit in a register helps you do that in a computer chip.

Turning off a specific feature in a hardware control register without affecting other features.
Disabling an interrupt by clearing its enable bit in a microcontroller.
Resetting a status flag bit after handling an event.
Controlling individual LEDs connected to bits in a port register by turning one off.
Modifying configuration bits in a device register safely.
Syntax
Embedded C
register &= ~(1U << bit_position);

register is the variable holding the bits.

bit_position is the number of the bit you want to clear, starting from 0 for the least significant bit.

Examples
This clears bit 3 of PORTA, turning off that specific bit.
Embedded C
PORTA &= ~(1U << 3);
This clears the least significant bit (bit 0) of status_register.
Embedded C
status_register &= ~(1U << 0);
This clears the highest bit (bit 7) in an 8-bit control_reg.
Embedded C
control_reg &= ~(1U << 7);
Sample Program

This program starts with all bits set to 1 in an 8-bit register. It clears bit number 4 and prints the register value before and after clearing.

Embedded C
#include <stdio.h>

int main() {
    unsigned char reg = 0b11111111; // all bits set to 1
    int bit_to_clear = 4;

    printf("Before clearing bit %d: 0x%02X\n", bit_to_clear, reg);

    reg &= ~(1U << bit_to_clear); // clear bit 4

    printf("After clearing bit %d: 0x%02X\n", bit_to_clear, reg);

    return 0;
}
OutputSuccess
Important Notes

Bits are counted from 0 starting at the right (least significant bit).

Using ~(1U << bit_position) creates a mask with all bits set to 1 except the bit you want to clear.

Make sure the register variable is the correct size to hold the bits you want to manipulate.

Summary

Clearing a bit means setting it to 0 without changing other bits.

Use register &= ~(1U << bit_position); to clear a specific bit.

This technique is useful for controlling hardware features bit by bit.