cbcef5ae3ef4f11c5a6d8630f51f2e282b76d843
1 # This is an unpipelined version of an sin/cos cordic, which will
2 # later be used to verify the operation of a pipelined version
4 # see http://bugs.libre-riscv.org/show_bug.cgi?id=208
5 from nmigen
import Module
, Elaboratable
, Signal
, Memory
, signed
6 from nmigen
.cli
import rtlil
8 from enum
import Enum
, unique
12 class CordicState(Enum
):
17 class CordicROM(Elaboratable
):
18 def __init__(self
, fracbits
, iterations
):
19 self
.fracbits
= fracbits
20 self
.iterations
= iterations
23 self
.addr
= Signal(range(iterations
))
24 self
.data
= Signal(range(-M
, M
-1))
26 angles
= [int(round(M
*math
.atan(2**(-i
))))
27 for i
in range(self
.iterations
)]
29 self
.mem
= Memory(width
=self
.data
.width
,
30 depth
=self
.iterations
,
33 def elaborate(self
, platform
):
35 m
.submodules
.rdport
= rdport
= self
.mem
.read_port()
36 m
.d
.comb
+= rdport
.addr
.eq(self
.addr
)
37 m
.d
.comb
+= self
.data
.eq(rdport
.data
)
41 class CORDIC(Elaboratable
):
42 def __init__(self
, fracbits
):
43 self
.fracbits
= fracbits
44 self
.M
= M
= (1 << fracbits
)
45 self
.ZMAX
= ZMAX
= int(round(self
.M
* math
.pi
/2))
47 # sin/cos output in 0.ffffff format
48 self
.cos
= Signal(range(-M
, M
+1), reset
=0)
49 self
.sin
= Signal(range(-M
, M
+1), reset
=0)
51 self
.z0
= Signal(range(-ZMAX
, ZMAX
), reset_less
=True)
54 self
.start
= Signal(reset_less
=True)
55 # cordic done/ready for input
56 self
.ready
= Signal(reset
=True)
58 self
.width
= self
.z0
.width
59 self
.iterations
= self
.width
- 1
61 def elaborate(self
, platform
):
67 # Calculate initial amplitude?
69 for i
in range(self
.iterations
):
70 An
*= math
.sqrt(1 + 2**(-2*i
))
72 X0
= int(round(self
.M
*1/An
))
73 x
= Signal(self
.sin
.shape())
74 y
= Signal(self
.sin
.shape())
75 z
= Signal(self
.z0
.shape())
76 dx
= Signal(self
.sin
.shape())
77 dy
= Signal(self
.sin
.shape())
78 dz
= Signal(self
.z0
.shape())
79 i
= Signal(range(self
.iterations
))
80 state
= Signal(CordicState
, reset
=CordicState
.WAITING
)
82 m
.submodules
.anglerom
= anglerom
= \
83 CordicROM(self
.fracbits
, self
.iterations
)
87 comb
+= dz
.eq(anglerom
.data
)
88 comb
+= self
.cos
.eq(x
)
89 comb
+= self
.sin
.eq(y
)
90 with m
.If(state
== CordicState
.WAITING
):
91 with m
.If(self
.start
):
96 sync
+= self
.ready
.eq(0)
97 sync
+= state
.eq(CordicState
.RUNNING
)
98 sync
+= anglerom
.addr
.eq(1)
99 with m
.If(state
== CordicState
.RUNNING
):
108 with m
.If(i
== self
.iterations
- 1):
109 sync
+= state
.eq(CordicState
.WAITING
)
110 sync
+= self
.ready
.eq(1)
111 sync
+= anglerom
.addr
.eq(0)
114 sync
+= anglerom
.addr
.eq(i
+2)
118 return [self
.cos
, self
.sin
, self
.z0
,
119 self
.ready
, self
.start
]
121 if __name__
== '__main__':
123 vl
= rtlil
.convert(dut
, ports
=dut
.ports())
124 with
open("cordic.il", "w") as f
: