|
| 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 FsmPs2data.sv |
| 10 | +object HdlBitsFsmPs2data extends App { |
| 11 | + ChiselStage.emitSystemVerilogFile( |
| 12 | + new HdlBitsFsmPs2data, |
| 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_ps2data |
| 22 | +class HdlBitsFsmPs2data extends RawModule { |
| 23 | + val clk = IO(Input(Clock())) |
| 24 | + val reset = IO(Input(Bool())) // Synchronous reset |
| 25 | + val in = IO(Input(UInt(8.W))) |
| 26 | + val out_bytes = IO(Output(UInt(24.W))) |
| 27 | + val done = IO(Output(Bool())) |
| 28 | + |
| 29 | + // Define state parameters |
| 30 | + val idle :: byte1 :: byte2 :: byte3 :: Nil = Enum(4) |
| 31 | + val nextState = WireInit( |
| 32 | + idle |
| 33 | + ) // NOTE: This is a default value, missing which will cause a compile error |
| 34 | + |
| 35 | + // State register with clock and reset |
| 36 | + val state = withClockAndReset(clk, reset) { RegInit(idle) } |
| 37 | + val dataPath = withClockAndReset(clk, reset) { RegInit(0.U(24.W)) } |
| 38 | + |
| 39 | + // State transition logic |
| 40 | + switch(state) { |
| 41 | + is(idle) { |
| 42 | + when(in(3)) { |
| 43 | + nextState := byte1 |
| 44 | + } |
| 45 | + } |
| 46 | + is(byte1) { |
| 47 | + nextState := byte2 |
| 48 | + } |
| 49 | + is(byte2) { |
| 50 | + nextState := byte3 |
| 51 | + } |
| 52 | + is(byte3) { |
| 53 | + when(in(3)) { |
| 54 | + nextState := byte1 |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // State update |
| 60 | + state := nextState |
| 61 | + dataPath := (dataPath << 8) | in // NOTE: different bit width is NOT warned by Chisel |
| 62 | + |
| 63 | + // Output logic |
| 64 | + out_bytes := dataPath |
| 65 | + done := state === byte3 |
| 66 | +} |
0 commit comments