1、控制器由状态机编写
module traffic_light (clk,rst_n,count,ew,sn);
input clk,rst_n;
input [5:0]count;//count input
output [2:0] ew,sn;//light
reg [2:0] ew,sn;
reg [1:0] pre_state,next_state;
parameter S0=2'b00,
S1=2'b01,
S2=2'b10,
S3=2'b11;
//state change block
always@(posedge clk or negedge rst_n)
begin
if (!rst_n)
pre_state<=S0;
else
pre_state<=next_state;
end
//激励方程
always@(count or pre_state)
begin
next_state<=3'bxxx;
if (count==6'd25)
next_state<=S1;
else if (count==6'd30)
next_state<=S2;
else if (count==6'd55)
next_state<=S3;
else if (count==6'd60)
next_state<=S0;
else
next_state<=pre_state;
end
//输出方程
always@(pre_state)
begin
case(pre_state)
S0: begin ew<=3'b100;sn<=3'b001;end
S1: begin ew<=3'b100;sn<=3'b010;end
S2: begin ew<=3'b001;sn<=3'b100;end
S3: begin ew<=3'b010;sn<=3'b100;end
default: begin ew<=3'b100;sn<=3'b001;end
endcase
end
endmodule
2、计数器
module counter(clk,rst_n,out,en);
input clk,rst_n,en;
output [5:0] out;
reg [5:0]out;
always@(posedge clk or negedge rst_n)
begin
if (!rst_n)
out<=6'd0;
else if (!en)
out<=out;
else if (out==6'd60)
out<=6'd0;
else
out<=out+1'b1;
end
endmodule
3、顶层模块
module top (clk,rst_n,en,ew,sn);
input clk,rst_n,en;
output [2:0] ew,sn;
wire [5:0]count;
wire [2:0]ew,sn;
counter U1(.clk(clk),
.rst_n(rst_n),
.out(count),
.en(en));
traffic_light U2(.clk(clk),
.rst_n(rst_n),
.count(count),
.ew(ew),
.sn(sn));
endmodule
4、测试文件
module top_tb;
reg clk,rst_n,en;
wire [2:0]ew,sn;
top U1(.clk(clk),
.rst_n(rst_n),
.en(en),
.ew(ew),
.sn(sn));
initial
begin
clk=1'b0;
forever #50 clk=~clk;
end
initial
begin
rst_n=1'b1;
en=1'b0;
#20 rst_n=1'b0;
#20 rst_n=1'b1;en=1'b1;
end
endmodule