Skip to content

Ard Bit Set

DodaTech 1 min read

In this tutorial, you'll learn about Arduino Setting a Bit Does Not Work. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Using bitwise OR to set a bit does not change the register value as expected.

Quick Fix

Wrong

DDRD |= 1 << 3;  // Sets bit 3 of DDRD
Bit 3 of DDRD is set (pin 3 becomes output). Works, but risky if used with read-modify-write on I/O registers.
// Use sbi macro for atomic set
// sbi(PORTD, 3);  // Available in <avr/sfr_defs.h>

// Safe bit set:
uint8_t flags = 0b00000000;
flags |= (1 << 3);  // Set bit 3
flags |= (1 << 5) | (1 << 6);  // Set bits 5 and 6

Serial.print("Flags: 0b");
Serial.println(flags, BIN);
Flags: 0b01101000  (bits 3, 5, 6 set).

Prevention

Setting a bit: flags |= (1 << bitNum). Clearing a bit: flags &= ~(1 << bitNum). Toggling: flags ^= (1 << bitNum). On AVR I/O registers, use the sbi()/cbi() macros for atomic operations. For regular variables, standard bitwise ops are fine.

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

FAQ

### What is the difference between (1 << n) and (1 << n) & mask?

1<<n targets a single bit. (1<<n) & mask would clear the bit if the mask has a 0 there. Use the direct form for setting bits.

Can I set multiple bits at once?

Yes: flags |= (1<<3) | (1<<5) | (1<<6). This sets all three bits in one operation.

What does sbi() do differently?

sbi() disables interrupts during the read-modify-write, preventing race conditions with ISRs. Only needed for I/O registers, not regular variables.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro