Elsia All Lessons

Embedded Systems

Bit Operations and a Binary Counter

In microcontroller programming, bits are managed one by one: the expression (n >> b) & 1 reads bit b of the number n; n |= (1<<b) sets the bit, n &= ~(1<<b) clears it.

Write the 4 bits of a counter to 4 LEDs and binary counting becomes visible: 0000, 0001, 0010… 1111. This is the fundamental logic of port expansion, LED matrices, and driving shift registers.

delay-based loops are simple but they block; to do several things at once, you switch to the non-blocking pattern of comparing timestamps with millis().

Formulas

bit = (n >> b) & 1
set: n | (1<<b)
clear: n & ~(1<<b)

⚡ Open this lesson in the simulator — free

Test Yourself

What is the value of (13 >> 2) & 1? (13 = 0b1101)
Answer: 1 — Bit 2 of 0b1101 (from the right, 0-based) = 1.
How many distinct values can 4 bits represent at most?
Answer: 16 — 2⁴ = 16 values (0–15).