2.4.1 Bit indexing

As an example, we will consider the design of a Gray encoder. The following code is a Gray encoder modeled in MyHDL:

from myhdl import Signal, delay, Simulation, always_comb, instance, intbv, bin

def bin2gray(B, G, width):
    """ Gray encoder.

    B -- input intbv signal, binary encoded
    G -- output intbv signal, gray encoded
    width -- bit width
    """
    
    @always_comb
    def logic():
        for i in range(width):
            G.next[i] = B[i+1] ^ B[i]
            
    return logic

This code introduces a few new concepts. The string in triple quotes at the start of the function is a doc string. This is standard Python practice for structured documentation of code.

Furthermore, we introduce a third decorator: always_comb.  It is used with a classic function and specifies that the resulting generator should wait for a value change on any input signal. This is typically used to describe combinatorial logic. The always_comb decorator automatically infers which signals are used as inputs.

Finally, the code contains bit indexing operations and an exclusive-or operator as required for a Gray encoder. By convention, the lsb of an intbv object has index 0.

To verify the Gray encoder, we write a test bench that prints input and output for all possible input values:

def testBench(width):
    
    B = Signal(intbv(0))
    G = Signal(intbv(0))
    
    dut = bin2gray(B, G, width)

    @instance
    def stimulus():
        for i in range(2**width):
            B.next = intbv(i)
            yield delay(10)
            print "B: " + bin(B, width) + "| G: " + bin(G, width)

    return dut, stimulus

We use the conversion function bin to get a binary string representation of the signal values. This function is exported by the myhdl package and supplements the standard Python hex and oct conversion functions.

As a demonstration, we set up a simulation for a small width:

sim = Simulation(testBench(width=3))
sim.run()

The simulation produces the following output:

% python bin2gray.py
B: 000 | G: 000
B: 001 | G: 001
B: 010 | G: 011
B: 011 | G: 010
B: 100 | G: 110
B: 101 | G: 111
B: 110 | G: 101
B: 111 | G: 100
StopSimulation: No more events

About this document