soc/cores/spi/SPIMaster: rewrite/simplify.
[litex.git] / test / test_spi.py
1 # This file is Copyright (c) 2019 Florent Kermarrec <florent@enjoy-digital.fr>
2 # License: BSD
3
4 import unittest
5
6 from migen import *
7
8 from litex.soc.cores.spi import SPIMaster, SPISlave
9
10
11 class TestSPI(unittest.TestCase):
12 def test_spi_master_syntax(self):
13 spi_master = SPIMaster(pads=None, data_width=32, sys_clk_freq=100e6, spi_clk_freq=5e6)
14 self.assertEqual(hasattr(spi_master, "pads"), 1)
15
16 def test_spi_master_xfer_loopback_32b_32b(self):
17 def generator(dut):
18 yield dut.loopback.eq(1)
19 yield dut.clk_divider.eq(2)
20 yield dut.mosi.eq(0xdeadbeef)
21 yield dut.length.eq(32)
22 yield dut.start.eq(1)
23 yield
24 yield dut.start.eq(0)
25 yield
26 while (yield dut.done) == 0:
27 yield
28 yield
29 self.assertEqual(hex((yield dut.miso)), hex(0xdeadbeef))
30
31 dut = SPIMaster(pads=None, data_width=32, sys_clk_freq=100e6, spi_clk_freq=5e6, with_csr=False)
32 run_simulation(dut, generator(dut))
33
34 def test_spi_master_xfer_loopback_32b_16b(self):
35 def generator(dut):
36 yield dut.loopback.eq(1)
37 yield dut.mosi.eq(0xbeef)
38 yield dut.length.eq(16)
39 yield dut.start.eq(1)
40 yield
41 yield dut.start.eq(0)
42 yield
43 while (yield dut.done) == 0:
44 yield
45 yield
46 self.assertEqual(hex((yield dut.miso)), hex(0xbeef))
47
48 dut = SPIMaster(pads=None, data_width=32, sys_clk_freq=100e6, spi_clk_freq=5e6, with_csr=False, mode="aligned")
49 run_simulation(dut, generator(dut))
50
51 def test_spi_slave_syntax(self):
52 spi_slave = SPISlave(pads=None, data_width=32)
53 self.assertEqual(hasattr(spi_slave, "pads"), 1)
54
55 def test_spi_slave_xfer(self):
56 class DUT(Module):
57 def __init__(self):
58 pads = Record([("clk", 1), ("cs_n", 1), ("mosi", 1), ("miso", 1)])
59 self.submodules.master = SPIMaster(pads, data_width=32,
60 sys_clk_freq=100e6, spi_clk_freq=5e6,
61 with_csr=False)
62 self.submodules.slave = SPISlave(pads, data_width=32)
63
64 def master_generator(dut):
65 for i in range(8):
66 yield
67 yield dut.master.mosi.eq(0xdeadbeef)
68 yield dut.master.length.eq(32)
69 yield dut.master.start.eq(1)
70 yield
71 yield dut.master.start.eq(0)
72 yield
73 while (yield dut.master.done) == 0:
74 yield
75 yield
76 self.assertEqual(hex((yield dut.master.miso)), hex(0x12345678))
77
78 def slave_generator(dut):
79 for i in range(8):
80 yield
81 yield dut.slave.miso.eq(0x12345678)
82 while (yield dut.slave.start) == 0:
83 yield
84 while (yield dut.slave.done) == 0:
85 yield
86 yield
87 self.assertEqual(hex((yield dut.slave.mosi)), hex(0xdeadbeef))
88 self.assertEqual((yield dut.slave.length), 32)
89
90 dut = DUT()
91 run_simulation(dut, [master_generator(dut), slave_generator(dut)])