// Define the pins for input and output
int pinGray[] = {2, 3, 4, 5}; // Input for Gray code from 4 dip switches
int pinBinary[] = {6, 7, 8, 9}; // Output for binary number to 4 LEDs
void setup() {
Serial.begin(115200);
// Configure the pins as input and output
for (int i=0; i<4; i++) {
pinMode(pinGray[i], INPUT_PULLUP);
pinMode(pinBinary[i], OUTPUT);
}
}
void loop() {
static uint16_t lastGray = 0xFFFF;
// Read the Gray code number from the dip switches
uint16_t gray = 0;
for (int i=0; i<4; i++) {
gray |= (!(digitalRead(pinGray[i]))) << i;
}
if (gray != lastGray) {
lastGray = gray;
Serial.print("\nGray Code In: 0b");
Serial.println(gray, BIN);
// Convert the Gray code to binary
uint8_t binary = gray;
for (int i=1; i<4; i++) {
binary ^= (gray >> i);
}
Serial.print("Binary Code Out: 0b");
Serial.println(binary, BIN);
// Write the binary number to the LEDs
for (int i=0; i<4; i++) {
digitalWrite(pinBinary[i], binary & (1 << i));
}
}
}