Skip to content

Ard Bit Clear

DodaTech 1 min read

In this tutorial, you'll learn about Arduino Clearing a Bit Accidentally Clears Other Bits. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Using bitwise AND to clear a bit also zeroes out other bits in the register.

Quick Fix

Wrong

DDRD &= ~(1 << 3);  // Clears only bit 3? No, safe for register
Only bit 3 is cleared. This is actually correct for bit clearing.
uint8_t flags = 0b11111111;
// Clear bit 2 (zero-indexed)
flags &= ~(1 << 2);

Serial.print("After clear bit 2: 0b");
Serial.println(flags, BIN);

// Clear multiple bits safely
flags &= ~((1 << 2) | (1 << 4));
Serial.print("After clear bits 2,4: 0b");
Serial.println(flags, BIN);
After clear bit 2: 0b11111011
After clear bits 2,4: 0b11101011

Prevention

flags &= ~(1 << n) safely clears bit n without affecting others. The ~ operator inverts only the selected bit mask. For multiple bits: flags &= ~((1<<n) | (1<<m)). On AVR I/O registers, use cbi() for atomic clear. For regular variables, the compound assignment is safe.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### Why does ~(1 << n) not affect other bits?

~(1 << n) inverts the mask. If (1<<n) = 0b00010000, then ~(1<<n) = 0b11101111. AND with this clears only bit 4.

What is cbi()?

cbi(address, bit) clears a bit in an I/O register atomically (interrupt-safe). Defined in <avr/sfr_defs.h>.

How do I clear all bits?

flags = 0; or flags &= 0; Both reset all bits to 0.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro