Bit Masking
Set, clear, toggle and test individual bits of a register using masks.
Easy
#define LED_PIN 5
PORTB |= (1 << LED_PIN); // set bit 5 (LED on)
PORTB &= ~(1 << LED_PIN); // clear bit 5 (LED off)
PORTB ^= (1 << LED_PIN); // toggle bit 5
if (PINB & (1 << 2)) { } // test bit 2 (button pressed?)
A mask is a value with 1s in the positions you care about. These four patterns appear in almost every piece of microcontroller code. Use volatile on hardware registers so the compiler doesn't optimise accesses away.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.