import migen in litex/gen
[litex.git] / litex / soc / misoc / cores / uart / test.py
1 # XXX Adapt test to new architecture
2 class UARTTB(Module):
3 def __init__(self):
4 self.clk_freq = 83333333
5 self.baud = 3000000
6 self.pads = Record([("rx", 1), ("tx", 1)])
7 self.submodules.slave = UART(self.pads, self.clk_freq, self.baud)
8
9 def wait_for(self, ns_time):
10 freq_in_ghz = self.clk_freq/(10**9)
11 period = 1/freq_in_ghz
12 num_loops = int(ns_time/period)
13 for i in range(num_loops+1):
14 yield
15
16 def gen_simulation(self, selfp):
17 baud_in_ghz = self.baud/(10**9)
18 uart_period = int(1/baud_in_ghz)
19 half_uart_period = int(1/(2*baud_in_ghz))
20
21 # Set TX an RX lines idle
22 selfp.pads.tx = 1
23 selfp.pads.rx = 1
24 yield
25
26 # First send a few characters
27
28 tx_string = "01234"
29 print("Sending string: " + tx_string)
30 for c in tx_string:
31 selfp.slave._r_rxtx.r = ord(c)
32 selfp.slave._r_rxtx.re = 1
33 yield
34 selfp.slave._r_rxtx.re = 0
35
36 yield from self.wait_for(half_uart_period)
37
38 if selfp.pads.tx:
39 print("FAILURE: no start bit sent")
40
41 val = 0
42 for i in range(8):
43 yield from self.wait_for(uart_period)
44 val >>= 1
45 if selfp.pads.tx:
46 val |= 0x80
47
48 yield from self.wait_for(uart_period)
49
50 if selfp.pads.tx == 0:
51 print("FAILURE: no stop bit sent")
52
53 if ord(c) != val:
54 print("FAILURE: sent decimal value "+str(val)+" (char "+chr(val)+") instead of "+c)
55 else:
56 print("SUCCESS: sent "+c)
57 while selfp.slave.ev.tx.trigger != 1:
58 yield
59
60 # Then receive a character
61
62 rx_string = '5'
63 print("Receiving character "+rx_string)
64 rx_value = ord(rx_string)
65 for i in range(11):
66 if (i == 0):
67 # start bit
68 selfp.pads.rx = 0
69 elif (i == 9):
70 # stop bit
71 selfp.pads.rx = 1
72 elif (i == 10):
73 selfp.pads.rx = 1
74 break
75 else:
76 selfp.pads.rx = 1 if (rx_value & 1) else 0
77 rx_value >>= 1
78 yield from self.wait_for(uart_period)
79
80 rx_value = ord(rx_string)
81 received_value = selfp.slave._r_rxtx.w
82 if (received_value == rx_value):
83 print("RX SUCCESS: ")
84 else:
85 print("RX FAILURE: ")
86
87 print("received "+chr(received_value))
88
89 while True:
90 yield
91
92 if __name__ == "__main__":
93 from migen.sim.generic import Simulator, TopLevel
94 from migen.sim import icarus
95 with Simulator(UARTTB(), TopLevel("top.vcd", clk_period=int(1/0.08333333)),
96 icarus.Runner(keep_files=False)) as s:
97 s.run(20000)