|
| 1 | +package hdlbits.circuits |
| 2 | + |
| 3 | +import chisel3._ |
| 4 | +import chisel3.util._ |
| 5 | + |
| 6 | +// _root_ disambiguates from package chisel3.util.circt if user imports chisel3.util._ |
| 7 | +import _root_.circt.stage.ChiselStage |
| 8 | + |
| 9 | +// Generate Verilog sources and save it in file Exams2014Q3fsm.sv |
| 10 | +object HdlBitsExams2014Q3fsm extends App { |
| 11 | + ChiselStage.emitSystemVerilogFile( |
| 12 | + new HdlBitsExams2014Q3fsm, |
| 13 | + firtoolOpts = Array( |
| 14 | + "-disable-all-randomization", |
| 15 | + "-strip-debug-info" |
| 16 | + ), |
| 17 | + args = Array("--target-dir", "gen/hdlbits/circuits") |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +// https://hdlbits.01xz.net/wiki/Exams/2014_q3_fsm |
| 22 | +class HdlBitsExams2014Q3fsm extends RawModule { |
| 23 | + val clk = IO(Input(Clock())) |
| 24 | + val reset = IO(Input(Bool())) // Synchronous reset |
| 25 | + val s = IO(Input(Bool())) |
| 26 | + val w = IO(Input(Bool())) |
| 27 | + val z = IO(Output(Bool())) |
| 28 | + |
| 29 | + // Define states as constants |
| 30 | + val a :: b0 :: b1 :: b2 :: Nil = Enum(4) |
| 31 | + |
| 32 | + // State registers with clock and reset |
| 33 | + val state = withClockAndReset(clk, reset) { RegInit(a) } |
| 34 | + val counter = withClockAndReset(clk, reset) { RegInit(0.U(2.W)) } |
| 35 | + |
| 36 | + // State transition logic |
| 37 | + switch(state) { |
| 38 | + is(a) { |
| 39 | + when(s) { |
| 40 | + state := b0 |
| 41 | + } |
| 42 | + } |
| 43 | + is(b0) { |
| 44 | + state := b1 |
| 45 | + when(w) { |
| 46 | + counter := 1.U |
| 47 | + }.otherwise { |
| 48 | + counter := 0.U |
| 49 | + } |
| 50 | + } |
| 51 | + is(b1) { |
| 52 | + state := b2 |
| 53 | + when(w) { |
| 54 | + counter := counter + 1.U |
| 55 | + } |
| 56 | + } |
| 57 | + is(b2) { |
| 58 | + state := b0 |
| 59 | + when(w) { |
| 60 | + counter := counter + 1.U |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // Output logic |
| 66 | + z := state === b0 && counter === 2.U |
| 67 | +} |
0 commit comments