记录学习日常:这两天在看状态机,这里给出一段式和三段式状态机的代码编写。上代码:
module haoxinren(
input clk,
input rst_n,
input [7:0]data,
output reg led
);
localparam
find_v = 4'b0001,
find_h = 4'b0010,
find_d = 4'b0100,
find_l = 4'b1000;
reg [3:0]state;
always@(posedge clk or negedge rst_n)
if(!rst_n)begin
led <= 1'b1;
state <= find_v;
end
else begin
case(state)
find_v:
if(data == "v")
state <= find_h;
else state <= find_v;
find_h:
if(data == "h")
state <= find_d;
//else if(data == "v")
//state <= find_h;
else state <= find_h;
find_d:
if(data == "d")
state <= find_l;
//else if(data == "v")
//state <= find_h;
else state <= find_d;
find_l:
//if(data == "v")
//state <= find_h;
//else begin
if(data == "l")begin
state <= find_v;
led <= ~led;
end
//if(data == "l")
//led <= ~led;
else
led <= led;
//end
default:state <= find_v;
endcase
end
/*
parameter find_v = 4'b0001;
parameter find_h = 4'b0010;
parameter find_d = 4'b0100;
parameter find_l = 4'b1000;
reg [3:0]now_state;
reg [3:0]next_state;
always@(posedge clk or negedge rst_n)
if(!rst_n)
now_state <= find_v;
else
now_state <= next_state;
always@(now_state or data)begin
case (now_state)
find_v : begin
if(data == "v")
next_state = find_h;
else
next_state = find_v;
end
find_h : begin
if(data == "h")
next_state = find_d;
else
next_state = find_h;
end
find_d : begin
if(data == "d")
next_state = find_l;
else
next_state = find_d;
end
find_l : begin
if(data == "l")
next_state = find_v;
else
next_state = find_l;
end
default : next_state = find_v;
endcase
end
always@(now_state)begin
if(now_state == find_l)
led <= 1'b1;
else
led <= 1'b0;
end*/
endmodule
通过led灯的反转来判断状态及的成功与否。测试文件如下
`timescale 1ns/1ns
`define clock_period 20
module haoxinren_tb;
reg clk;
reg rst_n;
wire led;
reg [7:0]ASCII;
haoxinren u_haoxinren(
.clk(clk),
.rst_n(rst_n),
.data(ASCII),
.led(led)
);
initial clk = 1;
always#(`clock_period/2)clk = ~clk;
initial begin
rst_n = 0;
ASCII = 0;
#(`clock_period*20);
rst_n = 1;
#(`clock_period*20+1);
forever begin
ASCII = "I";
#(`clock_period);
ASCII = "A";
#(`clock_period);
ASCII = "M";
#(`clock_period);
ASCII = "h";
#(`clock_period);
ASCII = "a";
#(`clock_period);
ASCII = "o";
#(`clock_period);
ASCII = "x";
#(`clock_period);
ASCII = "i";
#(`clock_period);
ASCII = "n";
#(`clock_period);
ASCII = "r";
#(`clock_period);
ASCII = "e";
#(`clock_period);
ASCII = "n";
#(`clock_period);
ASCII = "v";
#(`clock_period);
ASCII = "h";
#(`clock_period);
ASCII = "d";
#(`clock_period);
ASCII = "l";
#(`clock_period);
ASCII = "a";
#(`clock_period);
ASCII = "E";
#(`clock_period);
ASCII = "L";
#(`clock_period);
ASCII = "L";
#(`clock_period);
ASCII = "O";
#(`clock_period);
ASCII = "H";
#(`clock_period);
ASCII = "e";
#(`clock_period);
ASCII = "l";
#(`clock_period);
ASCII = "l";
#(`clock_period);
ASCII = "o";
#(`clock_period);
ASCII = "l";
end
end
endmodule
仿真波形如下:
在此实验工程中出现了一个严重问题就是:状态的跳转的条件考虑不周全,这只是个简单的状态机,相信在以后会接触越来越多转换条件的状态机。如有问题一起讨论一起进步。