源码:
module XLJC(
input clk,
input rst,
input code,
output reg code_out,
output reg code_mealy_out
);
parameter IDLE=6’b000001;
parameter S1=6’b000010;
parameter S2=5’b000100;
parameter S3=5’b001000;
parameter S4=5’b010000;
parameter S5=5’b100000;
reg [5:0] current_state,next_state;
always@(posedge clk or negedge rst)
begin
if(~rst)
current_state<=IDLE;
else
current_state<=next_state;
end
always@(*)
begin
next_state=IDLE;
case(current_state)
IDLE: if(code0) next_state=IDLE; else next_state=S1;
S1: if(code0) next_state=S2; else next_state=S1;
S2: if(code0) next_state=S3; else next_state=S1;
S3: if(code0) next_state=IDLE; else next_state=S4;
S4: if(code0) next_state=S5; else next_state=S1;
S5: if(code0) next_state=S3; else next_state=S1;
default:next_state=IDLE;
endcase
end
//more 状态
always@(posedge clk or negedge rst)
begin
if(~rst)
code_out<=0;
else
case(current_state)
IDLE: code_out<=0;
S1: code_out<=0;
S2: code_out<=0;
S3: code_out<=0;
S4: code_out<=0;
S5: code_out<=1;
default:code_out<=0;
endcase
end
//mealy 状态
always@(posedge clk or negedge rst)
begin
if(~rst)
code_mealy_out<=0;
else
begin
code_mealy_out<=(current_stateS4&&code0)?1’b1:1’b0;
end
end
endmodule
激励:
`timescale 1ns/1ns
module XLJC_tb();
reg clk;
reg rst;
reg code;
initial
begin
rst=0;
#100 rst=1;
#10000 $stop;
end
initial
begin
clk=0;
end
always #10 clk<=~clk;
always@(posedge clk or negedge rst)
begin
if(~rst)
code<=0;
else
code<={$random}%2;
end
XLJC XLJC_inist(
.clk(clk),
.rst(rst),
.code(code),
.code_out(),
.code_mealy_out()
);
endmodule
原理思想:先将这个任务的状态提炼出来,我们把这个任务分为6个状态,然后写出状态机。在运用三段式状态将它写出来。
三段式的写法:
****always@(posedge clk)
begin
if(~rst)
current-state<=IDLE;
else
current-state<=next_state;
end
always@(*)
begin
case(current_state)
状态转移条件:next_state=xxx;
end
always@(posedge clk)
begin
给各个状态赋值;
end****
随机数的写法: code<={$random}%2;
Moore:输出只与当前状态有关。
Mealy:输出与当前状态和输入有关。