`timescale 1ns/1ns
module sequence_detect(
input clk,
input rst_n,
input a,
output reg match
);
reg [7:0] reg_num;
// 通过移位和拼接的方式输入序列存储
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
reg_num <= 8'b0;
else
reg_num <= {reg_num[7:0], a};
end
//进行序列比对
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
match <= 1'b0;
else begin
if(reg_num == 8'b01_110_001)
match <= 1'b1;
else
match <= 1'b0;
end
end
/* 状态机解法
reg [8:0] cur_state ;
reg [8:0] nex_state ;
parameter IDLE = 9'b000_000_001,
S0 = 9'b000_000_010,
S1 = 9'b000_000_100,
S2 = 9'b000_001_000,
S3 = 9'b000_010_000,
S4 = 9'b000_100_000,
S5 = 9'b001_000_000,
S6 = 9'b010_000_000,
S7 = 9'b100_000_000;
/////////////三段式状态机//////////////////
//第一段: 时序逻辑描述状态转换关系
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
cur_state <= IDLE ;
else
cur_state <= nex_state ;
end
//第一段: 组合逻辑描述状态转换逻辑
always@(*)begin
case(cur_state)
IDLE: begin
if(a == 1'b0)
nex_state = S0 ;
else
nex_state = IDLE ;
end
S0: begin
if(a == 1'b1)
nex_state = S1 ;
else
nex_state = S0 ;
end
S1: begin
if(a == 1'b1)
nex_state = S2 ;
else
nex_state = S0 ;
end
S2: begin
if(a == 1'b1)
nex_state = S3 ;
else
nex_state = S0 ;
end
S3: begin
if(a == 1'b0)
nex_state = S4 ;
else
nex_state = IDLE ;
end
S4: begin
if(a == 1'b0)
nex_state = S5 ;
else
nex_state = IDLE ;
end
S5: begin
if(a == 1'b0)
nex_state = S6 ;
else
nex_state = IDLE ;
end
S6: begin
if(a == 1'b1)
nex_state = S7 ;
else
nex_state = S0 ;
end
default: nex_state = IDLE;
endcase
end
//第三段, 时序逻辑描述输出
always@(posedge clk or negedge rst_n)begin
if(!rst_n)
match <= 1'b0;
else begin
case(cur_state)
S7: match <= 1'b1;
default : match <= 1'b0;
endcase
end
end
*/
endmodule
对于序列检测题目,常规的解法有两种:状态机法和序列缓存对比法。
状态机法的过程类似于题意理解中提到的过程:在初始状态中,先判断第一位是否符合,若符合则进入下一个状态,判断第二位是否符合;若第一位不符合则保持在初始状态,直到第一位匹配。如前两位匹配,则判断第三位是否符合,若第一位匹配,最新输入的数值和目标序列的第二位不匹配,则根据最新一位是否匹配第一位,进入第一位匹配状态或者初始状态。依次类推。
序列缓存对比法,则是将八个时刻的数据缓存,作为一个数组,每个时刻的输入位于数组的末尾,数组其它元素左移,把最早输入的数据移出。然后将数组和目标序列对比,如果数组和目标序列相等,则说明出现目标序列。
为了练习三段式状态机的写法,本题两种解法来构造。

京公网安备 11010502036488号