3.2.1.2 Example

The following is an example of a combinatorial multiplexer:

from myhdl import Signal, Simulation, delay, always_comb

def Mux(z, a, b, sel):

    """ Multiplexer.
    
    z -- mux output
    a, b -- data inputs
    sel -- control input: select a if asserted, otherwise b

    """

    @always_comb
    def muxLogic():
        if sel == 1:
            z.next = a
        else:
            z.next = b

    return muxLogic

To verify it, we will simulate the logic with some random patterns. The random module in Python's standard library comes in handy for such purposes. The function randrange(n) returns a random natural integer smaller than n. It is used in the test bench code to produce random input values:

from random import randrange

z, a, b, sel = [Signal(0) for i in range(4)]

mux_1 = Mux(z, a, b, sel)

def test():
    print "z a b sel"
    for i in range(8):
        a.next, b.next, sel.next = randrange(8), randrange(8), randrange(2)
        yield delay(10)
        print "%s %s %s %s" % (z, a, b, sel)

test_1 = test()

sim = Simulation(mux_1, test_1)
sim.run()

Because of the randomness, the simulation output varies between runs 3.2. One particular run produced the following output:

% python mux.py
z a b sel
6 6 1 1
7 7 1 1
7 3 7 0
1 2 1 0
7 7 5 1
4 7 4 0
4 0 4 0
3 3 5 1
StopSimulation: No more events



Footnotes

... runs3.2
It also possible to have a reproducible random output, by explicitly providing a seed value. See the documentation of the random module.
About this document