Previous: 2.4 Bit
oriented operations Up: 2.4 Bit
oriented operations Next: 2.4.2 Bit
slicing
As an example, we will consider the design of a
Gray encoder. The following code is a Gray encoder modeled in MyHDL:
def bin2gray(B, G, width):
""" Gray encoder.
B -- input intbv signal, binary encoded
G -- output intbv signal, Gray encoded
width -- bit width
""" ###
while True: ###
yield B
for i in range(width):
G.next[i] = B[i+1] ^ B[i]
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.
Moreover, we use a third form of the yield statement: "yield signal". This specifies that the
generator should wait for a signal value change. ###1 This is typically used to describe
combinatorial logic. 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
. ###Q1 ###Ex1
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)
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 complements the standard Python hex
and oct
conversion functions.
To demonstrate, we set up a simulation for a small
width:
Simulation(testBench(width=3)).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
###1 Moreover, ... wait for a signal value change.
-->
Secondly, the yield statement
returns a Signal object. The
scheduler uses this object to call the generator whenever there is any change
in the signal.
Again, we are avoiding any confusion as to the behavior provided
by Python vs MyHDL.
Previous: 2.4 Bit
oriented operations Up: 2.4 Bit
oriented operations Next: 2.4.2 Bit
slicing
Release
0.4, documentation updated on February 4, 2004.