21a406ab478ea19aeb8d11c2a5e2433810e44654
[lambdasoc.git] / lambdasoc / test / test_periph_timer.py
1 #nmigen: UnusedElaboratable=no
2
3 import unittest
4
5 from nmigen import *
6 from nmigen.back.pysim import *
7
8 from ._wishbone import *
9 from ..periph.timer import TimerPeripheral
10
11
12 def simulation_test(dut, process):
13 with Simulator(dut, vcd_file=open("test.vcd", "w")) as sim:
14 sim.add_clock(1e-6)
15 sim.add_sync_process(process)
16 sim.run()
17
18
19 reload_addr = 0x00 >> 2
20 en_addr = 0x04 >> 2
21 ctr_addr = 0x08 >> 2
22 ev_status_addr = 0x10 >> 2
23 ev_pending_addr = 0x14 >> 2
24 ev_enable_addr = 0x18 >> 2
25
26
27 class TimerPeripheralTestCase(unittest.TestCase):
28 def test_invalid_width(self):
29 with self.assertRaisesRegex(ValueError,
30 r"Counter width must be a non-negative integer, not 'foo'"):
31 dut = TimerPeripheral(width="foo")
32
33 def test_invalid_width_32(self):
34 with self.assertRaisesRegex(ValueError,
35 r"Counter width cannot be greater than 32 \(was: 33\)"):
36 dut = TimerPeripheral(width=33)
37
38 def test_simple(self):
39 dut = TimerPeripheral(width=4)
40 def process():
41 yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf)
42 yield
43 ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf)
44 self.assertEqual(ctr, 15)
45 yield
46 yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf)
47 yield
48 for i in range(16):
49 yield
50 ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf)
51 self.assertEqual(ctr, 0)
52 simulation_test(dut, process)
53
54 def test_irq(self):
55 dut = TimerPeripheral(width=4)
56 def process():
57 yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf)
58 yield
59 yield from wb_write(dut.bus, addr=ev_enable_addr, data=1, sel=0xf)
60 yield
61 yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf)
62 yield
63 done = False
64 for i in range(16):
65 if (yield dut.irq):
66 self.assertFalse(done)
67 done = True
68 ctr = yield from wb_read(dut.bus, addr=ctr_addr, sel=0xf)
69 self.assertEqual(ctr, 0)
70 yield
71 self.assertTrue(done)
72 simulation_test(dut, process)
73
74 def test_reload(self):
75 dut = TimerPeripheral(width=4)
76 def process():
77 yield from wb_write(dut.bus, addr=reload_addr, data=15, sel=0xf)
78 yield
79 yield from wb_write(dut.bus, addr=ctr_addr, data=15, sel=0xf)
80 yield
81 yield from wb_write(dut.bus, addr=ev_enable_addr, data=1, sel=0xf)
82 yield
83 yield from wb_write(dut.bus, addr=en_addr, data=1, sel=0xf)
84 yield
85 irqs = 0
86 for i in range(32):
87 if (yield dut.irq):
88 irqs += 1
89 yield from wb_write(dut.bus, addr=ev_pending_addr, data=1, sel=0xf)
90 yield
91 # not an accurate measure, since each call to wb_write() adds a few cycles,
92 # but we can at least check that reloading the timer works.
93 self.assertEqual(irqs, 2)
94 simulation_test(dut, process)