1
0
mirror of https://github.com/myhdl/myhdl.git synced 2024-12-14 07:44:38 +08:00
myhdl/example/manual/sparseMemory.py

135 lines
2.2 KiB
Python
Raw Normal View History

2003-06-30 14:24:23 +00:00
import traceback
2005-12-14 11:38:23 +00:00
from myhdl import *
2003-03-06 09:25:29 +00:00
class Error(Exception):
pass
def sparseMemory(dout, din, addr, we, en, clk):
2003-03-06 19:10:15 +00:00
2003-03-06 09:25:29 +00:00
""" Sparse memory model based on a dictionary.
Ports:
dout -- data out
din -- data in
addr -- address bus
we -- write enable: write if 1, read otherwise
en -- interface enable: enabled if 1
clk -- clock input
"""
2005-12-14 11:38:23 +00:00
2003-03-06 19:10:15 +00:00
memory = {}
2005-12-14 11:38:23 +00:00
@always(clk.posedge)
def access():
if en:
if we:
memory[addr.val] = din.val
else:
dout.next = memory[addr.val]
return access
2003-03-06 19:10:15 +00:00
def sparseMemory2(dout, din, addr, we, en, clk):
2003-03-06 09:25:29 +00:00
2003-03-06 19:10:15 +00:00
""" Sparse memory model based on a dictionary.
Ports:
dout -- data out
din -- data in
addr -- address bus
we -- write enable: write if 1, read otherwise
en -- interface enable: enabled if 1
clk -- clock input
"""
2005-12-14 11:38:23 +00:00
2003-03-06 09:25:29 +00:00
memory = {}
2005-12-14 11:38:23 +00:00
@always(clk.posedge)
def access():
if en:
if we:
memory[addr.val] = din.val
else:
try:
dout.next = memory[addr.val]
except KeyError:
raise Error, "Uninitialized address %s" % hex(addr)
return access
2003-03-06 09:25:29 +00:00
dout, din, addr, we, en, clk = args = [Signal(0) for i in range(6)]
2003-03-06 19:10:15 +00:00
dut = sparseMemory2(*args)
2003-03-06 09:25:29 +00:00
def clkGen():
while 1:
yield delay(10)
clk.next = not clk
def read(address):
2005-12-14 11:38:23 +00:00
yield clk.negedge
2003-03-06 09:25:29 +00:00
en.next = 1
we.next = 0
addr.next = address
2005-12-14 11:38:23 +00:00
yield clk.posedge
2003-03-06 09:25:29 +00:00
yield delay(1)
en.next = 0
we.next = 0
def write(data, address):
2005-12-14 11:38:23 +00:00
yield clk.negedge
2003-03-06 09:25:29 +00:00
addr.next = address
din.next = data
en.next = 1
we.next = 1
2005-12-14 11:38:23 +00:00
yield clk.posedge
2003-03-06 09:25:29 +00:00
en.next = 0
we.next = 0
def test():
yield write(0x55, 0x55)
yield write(0x77, 0x77)
yield write(0x111, 0x111)
yield read(0x77)
print hex(dout)
yield read(0x55)
2003-03-06 19:10:15 +00:00
print hex(dout)
2003-03-06 09:25:29 +00:00
yield read(0x33)
2005-12-14 11:38:23 +00:00
raise StopSimulation
2003-03-06 09:25:29 +00:00
sim = Simulation(clkGen(), test(), dut)
2003-06-30 14:24:23 +00:00
def main():
try:
sim.run()
except:
traceback.print_exc()
2003-03-06 09:25:29 +00:00
2003-06-30 14:24:23 +00:00
if __name__ == '__main__':
main()
2003-03-06 09:25:29 +00:00