检测一段序列这里给出两种方法讨论:1.状态机;2.移位寄存器。例子:检测序列1011。
第一种方法:状态机。(这里采用一段式状态机)话不多说,上代码。
module fsm(
input clk,
input rst_n,
input din,
output reg led
);
reg [2:0] state;
localparam s_idle = 4'b0001,s_1 = 4'b0010,s_10 = 4'b0100,s_101 = 4'b1000;
always@(posedge clk or negedge rst_n)
if(!rst_n)begin
state <= s_idle;
led <= 1'b1;
end
else begin
case(state)
s_idle :
if(din == "1")
state <= s_1;
else state <= s_idle;
s_1 :
if(din == "0")
state <= s_10;
else state <= s_1;
s_10 :
if(din == "1")
state <= s_101;
else state <= s_10;
s_101 :
if(din == "1")begin
state <= s_idle;
led <= ~led;
end
else
led <= led;
default : state <= s_idle;
endcase
end
endmodule
第二种方法:移位寄存器。代码如下:
module xulie(
input clk,
input rst_n,
input din,
output reg match
);
reg [2:0] match_d;
always@(posedge clk or negedge rst_n)
if(!rst_n)
match_d <= 3'd0;
else
match_d <= {match_d[1:0] , din};
always@(posedge clk or negedge rst_n)
if(!rst_n)
match <= 1'b0;
else if(din && (match_d == 3'b101))
match <= 1'b1;
else if(match)
match <= 1'b0;
endmodule
仿真如图:在检测到1011序列后,match输出一高电平。
版权声明:本文为qq_43827140原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。