Previous Page

Up One Level

Next Page

The MyHDL manual

Contents

Index

Previous: 3.2.1.1 Template Up: 3.2.1 Combinatorial logic Next: 3.2.2 Sequential logic



3.2.1.2 Example

The following is an example of a combinatorial multiplexer:

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

    """ Multiplexer.

   

    z -- mux output

    a, b -- data inputs

    sel -- control input: select a if asserted, otherwise b

 

    """

    while 1:

        yield a, b, sel

        if sel == 1:

            z.next = a

        else:

            z.next = b

Alternatively, it could be written as follows, using always_comb():

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

 

    def muxlogic():

        if sel == 1:

            z.next = a

        else:

            z.next = b

 

    return always_comb(muxlogic)

To verify, let's simulate this 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)

       

Simulation(MUX_1, test()).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

###Ex1


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.


Previous Page

Up One Level

Next Page

The MyHDL manual

Contents

Index

Previous: 3.2.1.1 Template Up: 3.2.1 Combinatorial logic Next: 3.2.2 Sequential logic


Release 0.4, documentation updated on February 4, 2004.

About this document

1