PyRaspBeta

← All practice problems

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:

n01234567
Gray (bit 2 bit 1 bit 0)000001011010110111101100

Tip: the Gray code of n is n ^ (n >> 1); test a bit with (g >> bit) & 1.

More in LEDs & PWM