Skip to content

Instantly share code, notes, and snippets.

@GaryLee
Created May 31, 2025 04:25
Show Gist options
  • Save GaryLee/76ba42312a4705abdd5a28a748504bb9 to your computer and use it in GitHub Desktop.
Save GaryLee/76ba42312a4705abdd5a28a748504bb9 to your computer and use it in GitHub Desktop.
The solution of Fsm serialdp(https://hdlbits.01xz.net/wiki/Fsm_serialdp).
// Problem: https://hdlbits.01xz.net/wiki/Fsm_serialdp.
module top_module(
input clk,
input in,
input reset, // Synchronous reset
output [7:0] out_byte,
output done
); //
parameter START = 4'd0, BIT0 = 4'd1, BIT1 = 4'd2, BIT2 = 4'd3, BIT3 = 4'd4,
BIT4 = 4'd5, BIT5 = 4'd6, BIT6 = 4'd7, BIT7 = 4'd8, PARITY = 4'd9,
STOP = 4'd10, NOT_STOP = 4'd11, DONE = 4'd12;
logic [3:0] state, next_state;
logic odd, parity_check;
// State transition.
always @(*) begin
case (state)
START : next_state = ~in ? BIT0 : START;
BIT0: next_state = BIT1;
BIT1: next_state = BIT2;
BIT2: next_state = BIT3;
BIT3: next_state = BIT4;
BIT4: next_state = BIT5;
BIT5: next_state = BIT6;
BIT6: next_state = BIT7;
BIT7: next_state = PARITY;
PARITY: next_state = STOP;
STOP: next_state = in ? DONE : NOT_STOP;
NOT_STOP: next_state = in ? START : NOT_STOP;
DONE: next_state = ~in ? BIT0 : START;
default: next_state = START;
endcase
end
// State flip-flip.
always @(posedge clk) begin
state <= reset ? START : next_state;
end
// Output data path.
assign done = (state == DONE && parity_check);
// New: Datapath to latch input bits.
always @(posedge clk) begin
case (state)
BIT0: out_byte[0] <= in;
BIT1: out_byte[1] <= in;
BIT2: out_byte[2] <= in;
BIT3: out_byte[3] <= in;
BIT4: out_byte[4] <= in;
BIT5: out_byte[5] <= in;
BIT6: out_byte[6] <= in;
BIT7: out_byte[7] <= in;
STOP: parity_check <= odd;
endcase
end
// New: Add parity checking.
logic reset_parity;
assign reset_parity = (state == START || state == DONE);
parity u_parity(.clk(clk), .reset(reset_parity), .in(in), .odd(odd));
endmodule
module parity (
input clk,
input reset,
input in,
output reg odd);
always @(posedge clk)
if (reset) odd <= 0;
else if (in) odd <= ~odd;
endmodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment