RTL代码:
//实现序列1101
//状态机实现和移位寄存器两种方式实现
//状态机方式:
module fsm(
input clk,
input rst_n,
input data_in,
output reg flag
);
reg [4:0]c_state;
reg [4:0]n_state;
parameter s0 = 5'b00001;
parameter s1 = 5'b00010;
parameter s2 = 5'b00100;
parameter s3 = 5'b01000;
parameter s4 = 5'b10000;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
c_state <= s0;
else
c_state <= n_state;
end
always@(*)begin
case(c_state)
s0:begin
if(data_in) n_state = s1;
else n_state = s0;
end
s1:begin
if(data_in) n_state = s2;
else n_state = s0;
end
s2:begin
if(data_in) n_state = s1;
else n_state = s3;
end
s3:begin
if(data_in) n_state = s4;
else n_state = s0;
end
s4:begin
if(data_in) n_state = s1;
else n_state = s0;
end
endcase
end
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
flag <= 1'b0;
else if(n_state == s4)
flag <= 1'b1;
else
flag <= 1'b0;
end
endmodule
//移位寄存器方式:
module fsm(
input clk,
input rst_n,
input data_in,
output flag
);
reg [3:0]data_r;
parameter data = 4'b1101;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
data_r <= 'd0;
else
data_r <= {data_r[2:0],data_in};
end
assign flag = (data_r == data)? 1'b1:1'b0;
endmodule
仿真代码:
`timescale 1ns / 1ps
module fsm_tb;
reg clk;
reg rst_n;
reg data_in;
wire flag;
fsm fsm_inst(
.clk (clk),
.rst_n (rst_n),
.data_in (data_in),
.flag (flag)
);
initial clk = 0;
always#10 clk = ~clk;
initial begin
rst_n = 0;
data_in = 0;
#200;
rst_n = 1;
end
reg [7:0]data;
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
data <= 8'b10110110;
else
data <= {data[6:0],data[7]};
end
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
data_in <= 1'b0;
else
data_in <= data[7];
end
endmodule
**仿真:**注意两种仿真结果的区别