-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdder.scala
49 lines (43 loc) · 1.21 KB
/
Adder.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// See LICENSE.txt for license details.
package TutorialExamples
import Chisel._
//A n-bit adder with carry in and carry out
class Adder(val n: Int) extends Module {
val io = new Bundle {
val A = UInt(INPUT, n)
val B = UInt(INPUT, n)
val Cin = UInt(INPUT, 1)
val Sum = UInt(OUTPUT, n)
val Cout = UInt(OUTPUT, 1)
}
//create a vector of FullAdders
val FAs = Vec(n, Module(new FullAdder()).io)
val carry = Wire(Vec(n + 1, UInt(width = 1)))
val sum = Wire(Vec(n, Bool()))
//first carry is the top level carry in
carry(0) := io.Cin
//wire up the ports of the full adders
for (i <- 0 until n) {
FAs(i).a := io.A(i)
FAs(i).b := io.B(i)
FAs(i).cin := carry(i)
carry(i + 1) := FAs(i).cout
sum(i) := FAs(i).sum.toBool()
}
io.Sum := sum.toBits.toUInt()
io.Cout := carry(n)
}
class AdderTests(c: Adder) extends Tester(c) {
for (t <- 0 until 4) {
val rnd0 = rnd.nextInt(c.n)
val rnd1 = rnd.nextInt(c.n)
val rnd2 = rnd.nextInt(1)
poke(c.io.A, rnd0)
poke(c.io.B, rnd1)
poke(c.io.Cin, rnd2)
step(1)
val rsum = UInt(rnd0 + rnd1 + rnd2, width = c.n + 1)
expect(c.io.Sum, rsum(c.n - 1, 0).litValue())
expect(c.io.Cout, rsum(c.n).litValue())
}
}