这一题在上一题基础上多了一个输出,并且这个输出是不需要像上一题考虑出错的情况的,所以只要把输入in按次序排好就可以。我一开始的想法是在状态切换判断的always块里把in赋给out,但是不正确,代码如下:
cs
module top_module(
input clk,
input [7:0] in,
input reset, // Synchronous reset
output [23:0] out_bytes,
output done); //
parameter byte1=4'b0001, byte2=4'b0010, byte3=4'b0100, byte_fault=4'b1000;
reg [23:0] out_bytes_reg;
reg [3:0] state,next_state;
// State transition logic (combinational)
always@(*)begin
case(state)
byte1: begin
next_state = byte2; out_bytes_reg[23:16] = in[7:0];
end
byte2: begin
next_state = byte3; out_bytes_reg[15:8] = in[7:0];
end
byte3: begin
next_state = in[3]?byte1:byte_fault;
out_bytes_reg[7:0] = in[7:0];
end
byte_fault: begin
next_state = in[3]?byte1:byte_fault;
end
default: next_state = byte1;
endcase
end
// State flip-flops (sequential)
always@(posedge clk)begin
if(reset)
state <= byte_fault;
else
state <= next_state;
end
// Output logic
assign done = (state == byte3);
assign out_bytes = out_bytes_reg;
endmodule
看了大佬的写法,又改了思路,用一个always块专门实现这部分功能,如下:
cs
module top_module(
input clk,
input [7:0] in,
input reset, // Synchronous reset
output reg [23:0] out_bytes,
output done); //
// FSM from fsm_ps2
// New: Datapath to store incoming bytes.
parameter byte1=4'b0001, byte2=4'b0010, byte3=4'b0100, byte_fault=4'b1000;
reg [3:0] state,next_state;
// State transition logic (combinational)
always@(*)begin
case(state)
byte1: next_state = byte2;
byte2: next_state = byte3;
byte3: next_state = in[3]?byte1:byte_fault;
byte_fault: next_state = in[3]?byte1:byte_fault;
default: next_state = byte1;
endcase
end
// State flip-flops (sequential)
always@(posedge clk)begin
if(reset)
state <= byte_fault;
else
state <= next_state;
end
always@(posedge clk)begin
if(reset)
out_bytes <= 24'd0;
else
out_bytes <= {out_bytes[15:0],in[7:0]};
end
// Output logic
assign done = (state == byte3);
endmodule