Graycode Binary Upcounter Statement

04 Jun 2011

This is a simple 4 bit up counter.

Author: Christian Lerche
Date: 05-12-2009
MCU: LPC1768
Notes: Simple graycode upcounter, using onboard LEDs.

*/

#include "mbed.h"

BusOut LEDs(LED4, LED3, LED2, LED1);        // Make 4 bit bus with LEDs
unsigned char i;                            // Char to read for LEDs

int main() {                                // Main structure
    i=0;                                    // initialize i to 0
    while(1) {                              // While-loop (Do forever)
        LEDs=i^(i>>1);                      // This converts the binary to graycode
        wait(2);                            // Wait for .5 seconds
        i=i+1;                              // Every loop, add one to i
        if(i==16) {                         // If i is 16, make i 0
            i=0;                            // This makes it 0
        }                                   // End of if
    }                                       // End of while-loop (Do not anymore)
}                                           // End of main structure

Please can someone explain what the following statements actually do:

LEDs=i^(i>>1);

What does the '^' hat mean?

As I understand it 'i>>1' converts the binary to graycode But I have also seen 'i>>2' and 'i>>3'

Does this also convert it to graycode?

Cheers David

04 Jun 2011

The '^' hat means XOR (exclusive OR). This operation results in inverting the source bit for every digit position that has a '1' in the maskpattern. XOR truth table:

0 ^ 0 = 0

1 ^ 0 = 1

0 ^ 1 = 1

1 ^ 1 = 0

The 'i>>1' is a 1 position bitshift to the right. This results in a value that is divided by 2.

The resulting sequence for i=0 to i=15 is:

(0000) ^ (0000) = 0000;

(0001) ^ (0000) = 0001;

(0010) ^ (0001) = 0011;

(0011) ^ (0001) = 0010;

...

(1110) ^ (0111) = 1001;

(1111) ^ (0111) = 1000;

That results in a Graycode. Graycodes change only one bit between sequential values.