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.
Right
// 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro