Raspberry Pi practice problem · LEDs & PWM
Gray code
MediumBudget $5Python · gpiozero
In plain binary, going from 3 (011) to 4 (100) flips three bits at once. Gray code is an order where only one bit changes per step — rotary encoders use it for exactly that reason.
Three LEDs: bit 0 on GPIO17, bit 1 on GPIO27, bit 2 on GPIO22. Show the Gray code of 0, 1, 2, … 7, one value every 0.5 s starting at 0 s, then wrap back to 0 at 4.0 s and keep going:
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Gray (bit 2 bit 1 bit 0) | 000 | 001 | 011 | 010 | 110 | 111 | 101 | 100 |
Tip: the Gray code of n is n ^ (n >> 1); test a bit with (g >> bit) & 1.