On a small microcontroller, programs are often written in C or C++ (an Arduino sketch is C++). Numbers there have fixed sizes, and that causes some of the most confusing bugs in robotics.
Key idea
An 8-bit unsigned integer (uint8_t) holds 0 to 255; adding past 255 wraps around to 0. A 16-bit unsigned one holds 0 to 65,535. Bit masks work on single bits:
x | (1 << n) sets bit $n$, x & ~(1 << n) clears it, and x & (1 << n) tests it.Worked example: Overflow
A uint8_t holds 250. The program adds 10. What does it hold?
- $250 + 10 = 260$.
- 260 is more than 255, so it wraps: $260 - 256 = 4$.
Answer: 4.
Worked example: Set a bit
A register holds binary 0000 0101 (5). Set bit 3.
1 << 3is 0000 1000 (8).- OR them: 0000 1101.
Answer: 13.
Why it works
Encoder counts, timers and sensor registers all live in fixed-size integers. A robot whose distance suddenly jumps from 32,767 to β32,768 has hit a 16-bit signed overflow, not a broken sensor. Hardware registers pack many on-off settings into one byte, so bit masks are how you change one without disturbing the rest.
Common mistake
Expecting 250 + 10 to be 260 in an 8-bit variable, or clearing a bit with OR. OR can only set bits; to clear one, AND with the mask's complement.
Our Homeschool Code Practice page drills binary and hexadecimal, the number bases these masks are written in.