Gray Code Wiki

41
Synchronous Counters Questions and Answers Lee Chin Wei and Andrew Long Questions Answers References Questions : Note : there may be more than one right answer.

description

Gray code

Transcript of Gray Code Wiki

Page 2: Gray Code Wiki

1. What advantages do synchronous counters have over asynchronous counters?

A. Less likely to end up in erroneous states. B. Simpler to construct. C. Faster D. Consumes less power. 

Answer

2. The combinational element of a counter can be made with...

A. Flip-flops. B. Logic Gates. C. PLA (Programmable Logic Array) D. ROM (Read-Only Memory) 

Answer

3. What types of flip-flops can be used to implement the memory elements of a counter?

A. T flip-flips. B. JK flip-flops. C. D flip-flops. D. XY flip-flops. 

Answer

Page 3: Gray Code Wiki

4. What are the advantages of using a microprocessor to implement a counter rather than the conventional method (flip-flop and logic gates)?

A. Speed. B. Cost. C. Flexibility. D. Simpler to construct. 

Answer

5. Take a look at the diagram below.

What kind of counter is it?

A. Ripple counter. B. Johnson counter. C. BCD counter. D. Twisted-ring counter. 

Answer

Page 4: Gray Code Wiki

6. What is the principal advantage of Gray Code over straight (conventional) binary?

A. No intermediate states occur during transition.B. Bit positions in Gray Code have greater weights.C. Gray Codes are much easier to process.D. All of the above.

Answer

7. Convert 3267 to its BCD equivalent.

A. 0011 0010 1111 0000B. 0011 1111 0110 0111C. 0011 0010 0110 1110D. None of the above.

Answer

8. What is the principal function of the prescaler in the "pulse swallowing" technique?

A. To divide a fast incoming clock.B. To divide a binary number.C. Stops counter when too many pulses are received.D. None of the above.

Answer

Page 5: Gray Code Wiki

9. What does Pipelining do?

A. Predicts an event.B. Separates the detection of an event and the setting of certain output/s resulting from the event into two different clock periods.C. To store a value that is required in the next clock period.D. None of the above.

Answer

10. In Xilinx synchronous counters, how does the use of a prescaler increase the speed of the counter?

A. It increases the speed at which the bits toggle.B. It predicts subsequent values.C. It allows the carry ripple chain time to settle.D. All of the above.

Answer

Answers :

Page 6: Gray Code Wiki

A 1 :A. True. Since all inputs are synchronised with a common clock, no interrupts can occur in the middle of a state transition. 

B. False. Asynchronous counters are actually easier to construct as they usually require less combinational logic. 

C. True. In synchronous counters, all flip-flops change simultaneously and in asynchronous counters, the propagation delay of the flip-flops add up to produce the overall delay. Although synchronous counters usually have more combinational logic, the propogation delay through these gates are small compared to the propogation delay through many stages of flip-flops. 

D. False. Both types of flip-flops are made with similar components. 

A 2 :

A. False. Flip-flops are the memory elements of a counter. They cannot be used to implement combinational logic. 

B, C & D. True. All of these can be used to implement combinational logic. The PLA and ROM are similar except that the ROM needs to have every minterm defined, even though the system may never enter that state. The PLA only needs to have the minterms which are actually used defined. 

A 3 :

Page 7: Gray Code Wiki

A, B & C. True. Flip-flops are used mainly to "remember" the state of a sequential machine. All of these flip-flops can be used to implement this memory function. 

D. False. There is NO SUCH THING as an XY flip-flop. 

A 4 :

A. False. A microprocessor is usually much slower than a dedicated hardware device. A dedicated device can produce an output immediately on receiving an input signal while a microprocessor has to read in the signal, process the signal, increment program counter and write output etc. A dedicated device is usually a few orders of magnitude faster than a microprocessor. 

B. True/False. Whether a counter is more cost efficient to implement using a microprocessor or dedicated hardware depends on the size of the counter(s). For small systems, if would be cheaper to use dedicated hardware and vice versa. This is because for larger systems, a dedicated hardware system would need to add more flip-flops and logic gates whereas for microprocessors, we only need to write a different program for it. The number of states that can be implemented in a microprocessor is only limitted by the size of the program and the available memory area. 

C. True. A microprocessor is much more flexible. A dedicated hardware device, as its name suggests, can only perform the function it was designed to do. A single microprocessor can perform many different functions. 

Page 8: Gray Code Wiki

D. False. A microprocessor often needs several support chips, such as memory chips, to create a functioning system. It also needs to be programmed before it can be used. 

A 5 :

B & D. True. The diagram shows a Johnson counter, which is also known as a twisted ring counter. It has a feedback from the negated output back to its JK/T input. 

A 6 :

The answer is A. It is not only the principal advantage of Gray Code over straight binary but also the defining characteristic of Gray Code. The use of such a code limits errors to one bit position. This reduces the likelihood of unwanted transients during a state transition. This code is particularly suitable when analogue(continuous) data is being represented in binary.A 7 :The answer is D. The BCD equivalent is 0011 0010 0110 0111. To calculate this, each decimal digit is simply converted to its binary equivalent.A 8 :The answer is A. The main function of the prescaler is to divide a fast incoming clock and thereby provide a slower "clock" to the different sections(units and tens). The different sections only respond to this "clock" depending on the prescaler Mode(divide-by-11 or divide-by-10 etc).A 9 :

Page 9: Gray Code Wiki

A,B and C are essential functions of Pipelining. It predicts an event by detecting the state preceeeding the required state. Following this detection, a value is set and fed to the input of a Flip-flop(usually D-type). This effectively stores the value. The value will appear as the required output on the next clock pulse. The separation of the two events(detection and output setting) into two clock periods results in a much shorter clock period. Had the above actions been performed in a single clock period, the minimum clock period would have been significantly limited.A 10 :The answer is C. The prescaler generates an enable signal at a rate lower than(usually a factor of) the incoming clock rate. This difference in speed will give the carry ripple chain time to settle. If this were not done, the time taken for the carry ripple chain to settle has to be taken into account. This significantly limits the minimum clock period.

Rotary encoderFrom Wikipedia, the free encyclopedia

This article may require cleanup to meet Wikipedia's quality standards. Please improve this article if you can. The talk page may contain suggestions. (January 2008)

Page 10: Gray Code Wiki

A Gray code absolute rotary encoder with 13 tracks. At the top can be seen the housing, interrupter disk, and light

source; at the bottom can be seen the sensing element and support components.

A rotary encoder, also called a shaft encoder, is an electro-mechanical device that

converts the angular position of a shaft or axle to an analog or digital code, making it

an angle transducer. Rotary encoders are used in many applications that require

precise shaft unlimited rotation—including industrial controls, robotics, special

purpose photographic lenses [1] , computer input devices (such as

optomechanical mice and trackballs), and rotating radar platforms. There are two

main types: absolute and incremental (relative).

Contents

 [hide]

1   Absolute rotary encoder

o 1.1   Construction

o 1.2   Mechanical absolute encoders

o 1.3   Optical absolute encoders

o 1.4   Standard binary encoding

Page 11: Gray Code Wiki

o 1.5   Gray encoding

o 1.6   Single-track Gray encoding

o 1.7   Encoder output formats

2   Incremental rotary encoder

3   Incremental versus absolute encoder terminology

o 3.1   Traditional absolute encoders

o 3.2   Traditional incremental encoders

o 3.3   Battery backed incremental encoders

4   Sine wave encoder

5   Use in industry

o 5.1   Encoders used on servomotors

6   Encoder technologies

7   See also

8   External links

9   References

[edit]Absolute rotary encoder

Absolute rotary encoder ROD 425

[edit]Construction

Absolute digital type produces a unique digital code for each distinct angle of the

shaft. They come in two basic types: optical and mechanical.

[edit]Mechanical absolute encoders

A metal disc containing a set of concentric rings of openings is fixed to an insulating

disc, which is rigidly fixed to the shaft. A row of sliding contacts is fixed to a

stationary object so that each contact wipes against the metal disc at a different

Page 12: Gray Code Wiki

distance from the shaft. As the disc rotates with the shaft, some of the contacts touch

metal, while others fall in the gaps where the metal has been cut out. The metal

sheet is connected to a source of electric current, and each contact is connected to a

separate electrical sensor. The metal pattern is designed so that each possible

position of the axle creates a unique binary code in which some of the contacts are

connected to the current source (i.e. switched on) and others are not (i.e. switched

off).

[edit]Optical absolute encoders

The optical encoder's disc is made of glass or plastic with transparent and opaque

areas. A light source and photo detector array reads the optical pattern that results

from the disc's position at any one time.

This code can be read by a controlling device, such as a microprocessor or

microcontroller to determine the angle of the shaft.

The absolute analog type produces a unique dual analog code that can be translated

into an absolute angle of the shaft (by using a special algorithm).

[edit]Standard binary encoding

Rotary encoder for angle-measuring devices marked in 3-bit binary. The inner ring corresponds to Contact 1 in the

table. Black sectors are "on". Zero degrees is on the right-hand side, with angle increasing counterclockwise.

An example of a binary code, in an extremely simplified encoder with only three

contacts, is shown below.

Standard Binary Encoding

Page 13: Gray Code Wiki

Sector Contact 1 Contact 2 Contact 3 Angle

1 off off off 0° to 45°

2 off off ON 45° to 90°

3 off ON off 90° to 135°

4 off ON ON 135° to 180°

5 ON off off 180° to 225°

6 ON off ON 225° to 270°

7 ON ON off 270° to 315°

8 ON ON ON 315° to 360°

In general, where there are n contacts, the number of distinct positions of the shaft is

2n. In this example, n is 3, so there are 2³ or 8 positions.

In the above example, the contacts produce a standard binary count as the disc

rotates. However, this has the drawback that if the disc stops between two adjacent

sectors, or the contacts are not perfectly aligned, it can be impossible to determine

the angle of the shaft. To illustrate this problem, consider what happens when the

shaft angle changes from 179.9° to 180.1° (from sector 4 to sector 5). At some

instant, according to the above table, the contact pattern changes from off-on-on to

on-off-off. However, this is not what happens in reality. In a practical device, the

contacts are never perfectly aligned, so each switches at a different moment. If

contact 1 switches first, followed by contact 3 and then contact 2, for example, the

actual sequence of codes is:

off-on-on (starting position)

on-on-on (first, contact 1 switches on)

Page 14: Gray Code Wiki

on-on-off (next, contact 3 switches off)

on-off-off (finally, contact 2 switches off)

Now look at the sectors corresponding to these codes in the

table. In order, they are 4, 8, 7 and then 5. So, from the sequence

of codes produced, the shaft appears to have jumped from sector

4 to sector 8, then gone backwards to sector 7, then backwards

again to sector 5, which is where we expected to find it. In many

situations, this behaviour is undesirable and could cause the

system to fail. For example, if the encoder were used in a robot

arm, the controller would think that the arm was in the wrong

position, and try to correct the error by turning it through 180°,

perhaps causing damage to the arm.

[edit]Gray encoding

Rotary encoder for angle-measuring devices marked in 3-bit binary-reflected Gray code

(BRGC). The inner ring corresponds to Contact 1 in the table. Black sectors are "on".

Zero degrees is on the right-hand side, with angle increasing anticlockwise.

To avoid the above problem, Gray encoding is used. This is a

system of binary counting in which adjacent codes differ in only one

position. For the three-contact example given above, the Gray-coded

version would be as follows.

Gray Coding

Sector Contact 1 Contact 2 Contact 3 Angle

Page 15: Gray Code Wiki

1 off off off 0° to 45°

2 off off ON 45° to 90°

3 off ON ON 90° to 135°

4 off ON off 135° to 180°

5 ON ON off 180° to 225°

6 ON ON ON 225° to 270°

7 ON off ON 270° to 315°

8 ON off off 315° to 360°

In this example, the transition from sector 4 to sector 5, like all

other transitions, involves only one of the contacts changing its

state from on to off or vice versa. This means that the sequence

of incorrect codes shown in the previous illustration cannot

happen.

[edit]Single-track Gray encoding

If the designer moves a contact to a different angular position (but

at the same distance from the center shaft), then the

corresponding "ring pattern" needs to be rotated the same angle

to give the same output. If the most significant bit (the inner ring in

Figure 1) is rotated enough, it exactly matches the next ring out.

Since both rings are then identical, the inner ring can be omitted,

and the sensor for that ring moved to the remaining, identical ring

(but offset at that angle from the other sensor on that ring). Those

two sensors on a single ring make a quadrature encoder.

Page 16: Gray Code Wiki

For many years, Torsten Sillke and other mathematicians

believed that it was impossible to encode position on a single

track so that consecutive positions differed at only a single

sensor, except for the two-sensor, one-track quadrature encoder.

However, in 1994 N. B. Spedding registered a patent (NZ Patent

264738) showing it was possible with several examples.

See Single-track Gray code for details.

[edit]Encoder output formats

In commercial absolute encoders there are several formats for

transmission of absolute encoder data, including parallel

binary, SSI, "BiSS", ISI, Profibus, CAN

DeviceNet, CANopen, Endat and Hiperface, depending on the

manufacturer of the device

[edit]Incremental rotary encoder

Encoder ROD 420

An incremental rotary encoder, also known as a quadrature

encoder or a relative rotary encoder, has two outputs called

quadrature outputs. They can be either mechanical or optical. In

the optical type, there are two gray coded tracks, while the

mechanical type has two contacts that are actuated by cams on

the rotating shaft. The mechanical type requires debouncing and

is typically used as digital potentiometers on equipment including

consumer devices. Most modern home and car stereos use

mechanical rotary encoders for volume. Due to the fact the

mechanical switches requiredebouncing, the mechanical type are

limited in the rotational speeds they can handle. The incremental

Page 17: Gray Code Wiki

rotary encoder is the most widely used of all rotary encoders due

to its low cost: only two sensors are required.

The fact that incremental encoders use only two sensors does not

compromise their accuracy. One can find in the market

incremental encoders with up to 10,000 counts per revolution, or

more.

There can be an optional third output: reference, which happens

once every turn. This is used when there is the need of an

absolute reference, such as positioning systems.

The optical type is used when higher RPMs are encountered or a

higher degree of precision is required.

Incremental encoders are used to track motion and can be used

to determine position and velocity. This can be either linear or

rotary motion. Because the direction can be determined, very

accurate measurements can be made.

They employ two outputs called A & B, which are called

quadrature outputs, as they are 90 degrees out of phase.

The state diagram:

Gray coding forcounter-clockwise rotation

Phase A B

1 0 0

2 0 1

3 1 1

4 1 0

Gray coding forclockwise rotation

Phase A B

1 1 0

2 1 1

3 0 1

4 0 0

Page 18: Gray Code Wiki

Two square waves in quadrature (clockwise rotation).

The two output wave forms are 90 degrees out of phase, which is

all that the quadrature term means. These signals are decoded to

produce a count up pulse or a count down pulse. For decoding in

software, the A & B outputs are read by software, either via an

interrupt on any edge or polling, and the above table is used to

decode the direction. For example, if the last value was 00 and

the current value is 01, the device has moved one half step in the

clockwise direction. The mechanical types would be debounced

first by requiring that the same (valid) value be read a certain

number of times before recognizing a state change.

If the encoder is turning too fast, an invalid transition may occur,

such as 00->11. There is no way to know which way the encoder

turned; if it was 00->01->11, or 00->10->11.

If the encoder is turning even faster, a backward count may

occur. Example: consider the 00->01->11->10 transition (3 steps

forward). If the encoder is turning too fast, the system might read

only the 00 and then the 10, which yields a 00->10 transition (1

step backward).

This same principle is used in ball mice to track whether the

mouse is moving to the right/left or forward/backward.

Rotary sensors with a single output are not encoders and cannot

sense direction, but can sense RPM. They are thus

called tachometer sensors.

[edit]Incremental versus absolute encoder terminology

Page 19: Gray Code Wiki

There seem to be some grey areas as to what constitutes an

incremental encoder as opposed to an absolute encoder.

[edit]Traditional absolute encoders

Traditional absolute encoders have multiple code rings with

various binary weightings which provide a data word representing

the absolute position of the encoder within one revolution. This

type of encoder is often referred to as a parallel absolute encoder.

The distinguishing feature of the absolute encoder is that it

reports the absolute position of the encoder to the electronics

immediately upon power-up with no need for indexing. [2]

[edit]Traditional incremental encoders

A traditional incremental encoder works differently by providing an

A and a B pulse output that provide no usable count information

in their own right. Rather, the counting is done in the external

electronics. The point where the counting begins depends on the

counter in the external electronics and not on the position of the

encoder. To provide useful position information, the encoder

position must be referenced to the device to which it is attached,

generally using an index pulse. The distinguishing feature of the

incremental encoder is that it reports an incremental change in

position of the encoder to the counting electronics.[2]

[edit]Battery backed incremental encoders

Some encoder manufacturers, such as Fanuc, have taken a

different approach to this terminology. These manufacturers use

absolute as their terminology for incremental encoders with a

battery backed up memory to store count information and provide

an absolute count immediately upon power up.[2]

[edit]Sine wave encoder

A variation on the Incremental encoder is the Sinewave Encoder.

Instead of producing two quadrature square waves, the outputs

are quadrature sine waves (a Sine and a Cosine). By performing

the arctangent function, arbitrary levels of resolution can be

achieved.

Page 20: Gray Code Wiki

[edit]Use in industry

[edit]Encoders used on servomotors

Rotary encoders are often used to track the position of the motor

shaft on permanent magnet brushless motors, which are

commonly used on CNC machines, robots, and other industrial

equipment. Incremental (Quadrature) encoders are used on

Induction Motor type servomotors, but absolute encoders are

used in Permanent Magnet Brushless Motors, where applicable.

In these applications, the feedback device (encoder) plays a vital

role in ensuring that the equipment operates properly. The

encoder synchronizes the relative rotor magnet and stator

winding positions to the current provided by the drive. Maximum

torque results if the current is applied to the windings when the

rotor magnets are in a particular position range relative to the

stator windings. The motor will perform poorly or not at all if this

timing is not adjusted correctly. Improper encoder alignment on

the motor can actually cause it to run backwards sometimes

resulting in a hazardous run away condition. Correct alignment is

absolutely essential to proper operation of these motors.[3]

[edit]Encoder technologies

Page 21: Gray Code Wiki

Hall-effect quadrature encoder, sensing gear teeth on the driveshaft of a robot vehicle.

Encoders may be implemented using a variety of technologies:

Conductive tracks. A series of copper pads etched onto a

PCB is used to encode the information. Contact brushes

sense the conductive areas. This form of encoder is now

rarely seen.

Optical. This uses a light shining onto a photodiode through

slits in a metal or glass disc. Reflective versions also exist.

This is one of the most common technologies.

Magnetic. Strips of magnetised material are placed on the

rotating disc and are sensed by a Hall-effect sensor

or magnetoresistive sensor. Hall effect sensors are also used

to sense gear teeth directly, without the need for a separate

encoder disc.

[edit] Position encoders

Rotary encoder for angle-measuring devices marked in 3-bit binary-reflected Gray code (BRGC)

Page 22: Gray Code Wiki

A Gray code absolute rotary encoder with 13 tracks. At the top can be seen the housing, interrupter disk, and light

source; at the bottom can be seen the sensing element and support components.

Gray codes are used in position encoders (linear encoders and rotary encoders), in preference to

straightforward binary encoding. This avoids the possibility that, when several bits change in the

binary representation of an angle, a misread will result from some of the bits changing before

others. Originally, the code pattern was electrically conductive, supported (in a rotary encoder) by

an insulating disk. Each track had its own stationary metal spring contact; one more contact made

the connection to the pattern. That common contact was connected by the pattern to whichever of

the track contacts were resting on the conductive pattern. However, sliding contacts wear out and

need maintenance, which favors optical encoders.

Regardless of the care in aligning the contacts, and accuracy of the pattern, a natural-binary code

would have errors at specific disk positions, because it is impossible to make all bits change at

exactly the same time as the disk rotates. The same is true of an optical encoder; transitions

between opaque and transparent cannot be made to happen simultaneously for certain exact

positions. Rotary encoders benefit from the cyclic nature of Gray codes, because consecutive

positions of the sequence differ by only one bit.

Page 23: Gray Code Wiki

Gray codeFrom Wikipedia, the free encyclopedia

2-bit Gray code

00011110

3-bit Gray code

000001011010110111101100

4-bit Gray code

0000000100110010011001110101010011001101111111101010101110011000

The reflected binary code, also known as Gray code after Frank Gray, is a binary

numeral system where two successive values differ in only one bit.

Page 24: Gray Code Wiki

The reflected binary code was originally designed to prevent spurious output

from electromechanical switches. Today, Gray codes are widely used to

facilitate error correction in digital communications such as digital terrestrial

television and some cable TV systems.

Contents

 [hide]

1   Name

2   History and practical application

o 2.1   Position encoders

o 2.2   Tower of Hanoi

o 2.3   Genetic algorithms

o 2.4   Karnaugh maps

o 2.5   Error correction

o 2.6   Communication between clock domains

2.6.1   Gray code counters and arithmetic

3   Motivation

4   Constructing an n-bit Gray code

5   Special types of Gray codes

o 5.1   n-ary Gray code

o 5.2   Balanced Gray code

o 5.3   Monotonic Gray codes

o 5.4   Beckett–Gray code

o 5.5   Snake-in-the-box codes

o 5.6   Single-track Gray code

6   See also

7   Footnotes

8   References

9   External links

[edit]Name

Page 25: Gray Code Wiki

Gray's patent introduces the term "reflected binary code"

Bell Labs researcher Frank Gray introduced the term reflected binary code in his

1947 patent application, remarking that the code had "as yet no recognized name".[1] He derived the name from the fact that it "may be built up from the conventional

binary code by a sort of reflection process".

The code was later named after Gray by others who used it. Two different 1953

patent applications give "Gray code" as an alternative name for the "reflected binary

code";[2][3] one of those also lists "minimum error code" and "cyclic permutation code"

among the names.[3] A 1954 patent application refers to "the Bell Telephone Gray

code".[4]

[edit]History and practical application

Reflected binary codes were applied to mathematical puzzles before they became

known to engineers. The French engineer Émile Baudot used Gray codes

in telegraphy in 1878. He received the French Legion of Honor medal for his work.

The Gray code is sometimes attributed, incorrectly,[5] to Elisha Gray (in Principles of

Pulse Code Modulation, K. W. Cattermole,[6] for example).

Frank Gray, who became famous for inventing the signaling method that came to be

used for compatible color television, invented a method to convert analog signals to

reflected binary code groups using vacuum tube-based apparatus. The method and

apparatus were patented in 1953 and the name of Gray stuck to the codes. The

"PCM tube" apparatus that Gray patented was made by Raymond W. Sears of Bell

Labs, working with Gray and William M. Goodall, who credited Gray for the idea of

the reflected binary code.[7]

Page 26: Gray Code Wiki

Part of front page of Gray's patent, showing PCM tube (10) with reflected binary code in plate (15)

The use of his eponymous codes that Gray was most interested in was to minimize

the effect of error in the conversion of analog signals to digital; his codes are still

used today for this purpose, and others.

[edit]Position encoders

Rotary encoder for angle-measuring devices marked in 3-bit binary-reflected Gray code (BRGC)

Page 27: Gray Code Wiki

A Gray code absolute rotary encoder with 13 tracks. At the top can be seen the housing, interrupter disk, and light

source; at the bottom can be seen the sensing element and support components.

Gray codes are used in position encoders (linear encoders and rotary encoders), in

preference to straightforward binary encoding. This avoids the possibility that, when

several bits change in the binary representation of an angle, a misread will result

from some of the bits changing before others. Originally, the code pattern was

electrically conductive, supported (in a rotary encoder) by an insulating disk. Each

track had its own stationary metal spring contact; one more contact made the

connection to the pattern. That common contact was connected by the pattern to

whichever of the track contacts were resting on the conductive pattern. However,

sliding contacts wear out and need maintenance, which favors optical encoders.

Page 28: Gray Code Wiki

Regardless of the care in aligning the contacts, and accuracy of the pattern, a

natural-binary code would have errors at specific disk positions, because it is

impossible to make all bits change at exactly the same time as the disk rotates. The

same is true of an optical encoder; transitions between opaque and transparent

cannot be made to happen simultaneously for certain exact positions. Rotary

encoders benefit from the cyclic nature of Gray codes, because consecutive

positions of the sequence differ by only one bit.

[edit]Tower of Hanoi

The binary-reflected Gray code can also be used to serve as a solution guide for

the Tower of Hanoi problem, as well a classical Chinese-rings puzzle and a

sequential mechanical puzzle mechanism.[5] It also forms a Hamiltonian cycle on

a hypercube, where each bit is seen as one dimension.

[edit]Genetic algorithms

Due to the Hamming distance properties of Gray codes, they are sometimes used

in Genetic Algorithms. They are very useful in this field, since mutations in the code

allow for mostly incremental changes, but occasionally a single bit-change can cause

a big leap and lead to new properties.

[edit]Karnaugh maps

Gray codes are also used in labelling the axes of Karnaugh maps.[8]

[edit]Error correction

In modern digital communications, Gray codes play an important role in error

correction. For example, in a digital modulation scheme such as QAM where data is

typically transmitted in symbols of 4 bits or more, the signal's constellation diagram is

arranged so that the bit patterns conveyed by adjacent constellation points differ by

only one bit. By combining this with forward error correctioncapable of correcting

single-bit errors, it is possible for a receiver to correct any transmission errors that

cause a constellation point to deviate into the area of an adjacent point. This makes

the transmission system less susceptible to noise.

[edit]Communication between clock domains

Digital logic designers use Gray codes extensively for passing multi-bit count

information between synchronous logic that operates at different clock frequencies.

The logic is considered operating in different "clock domains". It is fundamental to

the design of large chips that operate with many different clocking frequencies.

Page 29: Gray Code Wiki

[edit]Gray code counters and arithmetic

A typical use of Gray code counters is building a FIFO (first-in, first-out) data buffer

that has read and write ports that exist in different clock domains. The input and

output counters inside such a dual-port FIFO are often stored using Gray code to

prevent invalid transient states from being captured when the count crosses clock

domains.[9] The updated read and write pointers need to be passed between clock

domains when they change, to be able to track FIFO empty and full status in each

domain. Each bit of the pointers is sampled non-deterministically for this clock

domain transfer. So for each bit, either the old value or the new value is propagated.

Therefore, if more than one bit in the multi-bit pointer is changing at the sampling

point, a "wrong" binary value (neither new nor old) can be propagated. By

guaranteeing only one bit can be changing, Gray codes guarantee that the only

possible sampled values are the new or old multi-bit value. Typically Gray codes of

power-of-two length are used.

Sometimes digital buses in electronic systems are used to convey quantities that can

only increase or decrease by one at a time, for example the output of an event

counter which is being passed between clock domains or to a digital-to-analog

converter. The advantage of Gray codes in these applications is that differences in

the propagation delays of the many wires that represent the bits of the code cannot

cause the received value to go through states that are out of the Gray code

sequence. This is similar to the advantage of Gray codes in the construction of

mechanical encoders, however the source of the Gray code is an electronic counter

in this case. The counter itself must count in Gray code, or if the counter runs in

binary then the output value from the counter must be reclocked after it has been

converted to Gray code, because when a value is converted from binary to Gray

code, it is possible that differences in the arrival times of the binary data bits into the

binary-to-Gray conversion circuit will mean that the code could go briefly through

states that are wildly out of sequence. Adding a clocked register after the circuit that

converts the count value to Gray code may introduce a clock cycle of latency, so

counting directly in Gray code may be advantageous. A Gray code counter was

patented in 1962 US3020481, and there have been many others since. In recent

times a Gray code counter can be implemented as a state machine in Verilog. In

order to produce the next count value, it is necessary to have some combinational

logic that will increment the current count value that is stored in Gray code. Probably

the most obvious way to increment a Gray code number is to convert it into ordinary

Page 30: Gray Code Wiki

binary code, add one to it with a standard binary adder, and then convert the result

back to Gray code. This approach was discussed in a paper in 1996 [10] and then

subsequently patented by someone else in 1998 US5754614. Other methods of

counting in Gray code are discussed in a report by R. W. Doran, including taking the

output from the first latches of the master-slave flip flops in a binary ripple counter.[11]

Perhaps the most common electronic counter with the "only one bit changes at a

time" property is the Johnson counter.

[edit]Motivation

Many devices indicate position by closing and opening switches. If that device

uses natural binary codes, these two positions would be right next to each other:

...011100...

The problem with natural binary codes is that, with real (mechanical) switches, it is

very unlikely that switches will change states exactly in synchrony. In the transition

between the two states shown above, all three switches change state. In the brief

period while all are changing, the switches will read some spurious position. Even

without keybounce, the transition might look like 011 — 001 — 101 — 100. When

the switches appear to be in position 001, the observer cannot tell if that is the "real"

position 001, or a transitional state between two other positions. If the output feeds

into a sequential system (possibly via combinational logic) then the sequential

system may store a false value.

The reflected binary code solves this problem by changing only one switch at a time,

so there is never any ambiguity of position,

Dec Gray Binary 0 000 000 1 001 001 2 011 010 3 010 011 4 110 100 5 111 101 6 101 110 7 100 111

Page 31: Gray Code Wiki

Notice that state 7 can roll over to state 0 with only one switch change. This is called

the "cyclic" property of a Gray code. A good way to remember Gray coding is by

being aware that the least significant bit follows a repetitive pattern of 2. That is 11,

00, 11 etc. and the second digit follows a pattern of fours.

More formally, a Gray code is a code assigning to each of a contiguous set

of integers, or to each member of a circular list, a word of symbols such that each

two adjacent code words differ by one symbol. These codes are also known

assingle-distance codes, reflecting the Hamming distance of 1 between adjacent

codes. There can be more than one Gray code for a given word length, but the term

was first applied to a particular binary code for the non-negative integers, thebinary-

reflected Gray code, or BRGC, the three-bit version of which is shown above.

[edit]Constructing an n-bit Gray code

The first few steps of the reflect-and-prefix method.

The binary-reflected Gray code list for n bits can be generated recursively from the

list for n−1 bits by reflecting the list (i.e. listing the entries in reverse order),

concatenating the original list with the reversed list, prefixing the entries in the

original list with a binary 0, and then prefixing the entries in the reflected list with a

binary 1. For example, generating the n = 3 list from the n = 2 list:

2-bit list: 00, 01, 11, 10  

Reflected:   10, 11, 01, 00

Concatenated: 00, 01, 11, 10, 10, 11, 01, 00

Page 32: Gray Code Wiki

Prefix old entries with 0: 000, 001, 011, 010, 10, 11, 01, 00

Prefix new entries with 1: 000, 001, 011, 010, 110, 111, 101, 100

The one-bit Gray code is G1 = (0, 1). This can be thought of as built recursively as

above from a zero-bit Gray code G0 = { Λ } consisting of a single entry of zero length.

This iterative process of generating Gn+1 from Gn makes the following properties of

the standard reflecting code clear:

Gn is a permutation of the numbers 0, ... , 2n−1. (Each number appears

exactly once in the list.)

Gn is embedded as the first half of Gn+1.

Therefore the coding is stable, in the sense that once a binary number

appears in Gn it appears in the same position in all longer lists; so it makes sense

to talk about the reflective Gray code value of a number: G(m) = the m-th

reflecting Gray code, counting from 0.

Each entry in Gn differs by only one bit from the previous entry. (The

Hamming distance is 1.)

The last entry in Gn differs by only one bit from the first entry. (The code is

cyclic.)

These characteristics suggest a simple and fast method of translating a binary value

into the corresponding Gray code. Each bit is inverted if the next higher bit of the

input value is set to one. This can be performed in parallel by a bit-shift and

exclusive-or operation if they are available: the nth Gray code is obtained by

computing 

A similar method can be used to perform the reverse translation, but the computation

of each bit depends on the computed value of the next higher bit so it cannot be

performed in parallel. Assuming gi is the ith gray-coded bit (g0 being the most

significant bit), and bi is the ith binary-coded bit (b0 being the most-significant bit), the

reverse translation can be given recursively: b0 = g0, and 

To construct the binary-reflected Gray code iteratively, start with the code 0, and at

step i find the bit position of the least significant '1' in the binary representation of i -

Page 33: Gray Code Wiki

flip the bit at that position in the previous code to get the next code. The bit positions

start 0, 1, 0, 2, 0, 1, 0, 3, ... (sequence A007814 in OEIS).

[edit]