东西南北四个方向,两组交通灯轮流交替变换,其中,红灯时间为30个时间单位,绿灯时间为25个时间单位,黄灯时间为5个时间单位。
源代码:
1.状态机
module signal_light(clk,rst,count,light1,light2);
input clk,rst;
input [5:0]count;
output light1,light2;
reg[2:0] light1,light2;
reg[2:0]state;
parameter Idle=3'b000,
S1=3'b001,
S2=3'b010,
S3=3'b011,
S4=3'b100;
always@(posedge clk)
begin
if(!rst)
begin
state<=Idle;
light1<=3'b010;
light2<=3'b010;
end
else
case(state)
Idle: if(rst)
begin
state<=S1;
light1<=3'b100;
light2<=3'b001;
end
S1: if(count=='d25)
begin
state<=S2;
light1<=3'b100;
light2<=3'b010;
end
S2: if(count=='d30)
begin
state<=S3;
light1<=3'b001;
light2<=3'b100;
end
S3: if(count=='d55)
begin
state<=S4;
light1<=3'b010;
light2<=3'b100;
end
S4: if(count=='d60)
begin
state<=S1;
light1<=3'b100;
light2<=3'b001;
end
default: state<=Idle;
endcase
end
endmodule
2.计数器
module counter(clk,rst,count);
output count;
input clk,rst;
reg[5:0] count;
always@(posedge clk or negedge rst)
begin
if(!rst)
count<='d0;
else if(count<'d60)
count<=count+1;
else
count<='d1;
end
endmodule
3.顶层
module signal_light_top(count,clk,rst,light1,light2);
input clk,rst;
output[2:0] light1,light2;
output[5:0]count;wire[5:0] count;
counter u2(clk,rst,count);
signal_light u1(clk,rst,count,light1,light2);
endmodule
测试:
module traffic_lights_tb;
reg clk,rst;
wire[2:0] light1,light2;
wire[5:0]count;
signal_light_top u3(count,clk,rst,light1,light2);
always
#5 clk=~clk;
initial
begin
clk<=1;
rst<=0;
#5 rst<=1;
end
endmodule
仿真: