preveen-stack / test

0 stars 0 forks source link

chisel scala example #21

Open preveen-stack opened 1 year ago

preveen-stack commented 1 year ago
  1. First, create a new directory for your Chisel project:
$ mkdir my-chisel-project
$ cd my-chisel-project
  1. Create an SBT build file called build.sbt and add the following lines to it:
scalaVersion := "2.12.8"

libraryDependencies += "edu.berkeley.cs" %% "chisel3" % "3.3.2"

This sets the Scala version to 2.12.8 and adds the Chisel 3.3.2 dependency to your project.

  1. Create a new Scala file called Mux2.scala in the src/main/scala directory of your project, and paste in the example source code:
import chisel3._

class Mux2 extends Module {
  val io = IO(new Bundle {
    val sel = Input(UInt(1.W))
    val in0 = Input(UInt(1.W))
    val in1 = Input(UInt(1.W))
    val out = Output(UInt(1.W))
  })

  when(io.sel === 0.U) {
    io.out := io.in0
  }.otherwise {
    io.out := io.in1
  }
}
  1. In the terminal, navigate to your project directory and run SBT:
$ sbt
  1. In the SBT shell, run the following command to compile your project:
sbt:my-chisel-project> compile

This will compile your Chisel code and generate Verilog code.

  1. You can then run the following command to generate a Verilog file for your Mux2 module:
sbt:my-chisel-project> runMain Mux2

This will generate a Verilog file called Mux2.v in the target/ directory.

  1. You can also use SBT to run tests. Create a new file called Mux2Spec.scala in the src/test/scala directory with the following contents:
import chisel3._
import chiseltest._
import org.scalatest._

class Mux2Spec extends FlatSpec with ChiselScalatestTester with Matchers {
  "Mux2" should "select the correct input" in {
    test(new Mux2) { c =>
      c.io.sel.poke(0.U)
      c.io.in0.poke(0.U)
      c.io.in1.poke(1.U)
      c.clock.step(1)
      c.io.out.expect(0.U)

      c.io.sel.poke(1.U)
      c.io.in0.poke(0.U)
      c.io.in1.poke(1.U)
      c.clock.step(1)
      c.io.out.expect(1.U)
    }
  }
}

This test uses the ChiselTest library to test the behavior of the Mux2 module. It sets the input values, advances the clock, and checks the output values to ensure that the MUX is selecting the correct input based on the sel input.

  1. To run the test, run the following command in the SBT shell:
sbt:my-chisel-project> test

This will compile and run your test, verifying the correctness of your Chisel code.