|
| 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 FsmPs2.sv |
| 10 | +object HdlBitsFsmHdlc extends App { |
| 11 | + ChiselStage.emitSystemVerilogFile( |
| 12 | + new HdlBitsFsmHdlc, |
| 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/Fsm_hdlc |
| 22 | +class HdlBitsFsmHdlc extends RawModule { |
| 23 | + val clk = IO(Input(Clock())) |
| 24 | + val reset = IO(Input(Bool())) // Synchronous reset |
| 25 | + val in = IO( |
| 26 | + Input(Bool()) |
| 27 | + ) |
| 28 | + val disc = IO(Output(Bool())) |
| 29 | + val flag = IO(Output(Bool())) |
| 30 | + val err = IO(Output(Bool())) |
| 31 | + |
| 32 | + // Define state parameters |
| 33 | + val dataS :: discS :: flagS :: errS :: Nil = Enum(4) |
| 34 | + |
| 35 | + // State register with clock and reset |
| 36 | + |
| 37 | + val state = withClockAndReset(clk, reset) { RegInit(dataS) } |
| 38 | + val counter = withClockAndReset(clk, reset) { |
| 39 | + RegInit(0.U(3.W)) |
| 40 | + } |
| 41 | + |
| 42 | + // State transition logic |
| 43 | + counter := Mux(in, counter + 1.U, 0.U) |
| 44 | + switch(state) { |
| 45 | + is(dataS) { |
| 46 | + when(counter === 5.U) { |
| 47 | + state := Mux(in, state, discS) |
| 48 | + }.elsewhen(counter === 6.U) { |
| 49 | + state := Mux(in, errS, flagS) |
| 50 | + } |
| 51 | + } |
| 52 | + is(discS) { |
| 53 | + state := dataS |
| 54 | + } |
| 55 | + is(flagS) { |
| 56 | + state := dataS |
| 57 | + } |
| 58 | + is(errS) { |
| 59 | + state := Mux(in, state, dataS) |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Output logic |
| 64 | + disc := state === discS |
| 65 | + flag := state === flagS |
| 66 | + err := state === errS |
| 67 | +} |
0 commit comments