2015-09-12 07:34:07 -04:00
|
|
|
from migen import *
|
2012-03-10 13:38:39 -05:00
|
|
|
|
2015-04-13 14:45:35 -04:00
|
|
|
|
2014-01-26 16:19:43 -05:00
|
|
|
# A slightly more elaborate counter.
|
2012-03-10 13:38:39 -05:00
|
|
|
# Has a clock enable (CE) signal, counts on more bits
|
|
|
|
# and resets with a negative number.
|
2013-07-24 12:47:25 -04:00
|
|
|
class Counter(Module):
|
2015-04-13 14:07:07 -04:00
|
|
|
def __init__(self):
|
|
|
|
self.ce = Signal()
|
|
|
|
# Demonstrate negative numbers and signals larger than 32 bits.
|
|
|
|
self.count = Signal((37, True), reset=-5)
|
2013-07-24 12:47:25 -04:00
|
|
|
|
2015-04-13 14:07:07 -04:00
|
|
|
self.sync += If(self.ce, self.count.eq(self.count + 1))
|
2014-10-17 05:08:37 -04:00
|
|
|
|
2015-09-11 00:44:14 -04:00
|
|
|
|
|
|
|
def counter_test(dut):
|
|
|
|
for cycle in range(20):
|
2015-04-13 14:07:07 -04:00
|
|
|
# Only assert CE every second cycle.
|
|
|
|
# => each counter value is held for two cycles.
|
2015-09-11 00:44:14 -04:00
|
|
|
if cycle % 2:
|
|
|
|
yield dut.ce, 0 # This is how you write to a signal.
|
2015-04-13 14:07:07 -04:00
|
|
|
else:
|
2015-09-11 00:44:14 -04:00
|
|
|
yield dut.ce, 1
|
|
|
|
print("Cycle: {} Count: {}".format(cycle, (yield dut.count)))
|
|
|
|
yield
|
2014-10-17 05:08:37 -04:00
|
|
|
|
2014-01-26 16:19:43 -05:00
|
|
|
# Output is:
|
|
|
|
# Cycle: 0 Count: -5
|
|
|
|
# Cycle: 1 Count: -5
|
|
|
|
# Cycle: 2 Count: -4
|
|
|
|
# Cycle: 3 Count: -4
|
|
|
|
# Cycle: 4 Count: -3
|
|
|
|
# ...
|
2012-03-10 13:38:39 -05:00
|
|
|
|
2014-01-26 16:19:43 -05:00
|
|
|
if __name__ == "__main__":
|
2015-04-13 14:07:07 -04:00
|
|
|
dut = Counter()
|
2015-09-11 00:44:14 -04:00
|
|
|
Simulator(dut, counter_test(dut)).run()
|