东西南北四个方向,两组交通灯轮流交替变换,其中,红灯时间为30个时间单位,绿灯时间为25个时间单位,黄灯时间为5个时间单位。
源代码:
1.状态机
module sig_contral(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 counter60(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.顶层
`include "sig_contral.v"
`include "counter60.v"
module signal_light_top (
input clk,
input rst,
output [2:0] light1, //[green, red, yellow]
output [2:0] light2, //[green, red, yellow]
output [5:0] count
);
counter60 counter(
.clk(clk),
.rst(rst),
.count(count)
);
sig_contral sig_contral2(
.clk(clk),
.rst(rst),
.light1(light1),
.light2(light2),
.count(count)
);
endmodule
测试:
`timescale 1ns/1ps
module traffic_2_tb;
parameter timecycle = 10;
reg clk;
reg rst;
wire [2:0] light1;
wire [2:0] light2;
wire [5:0] count;
initial begin
clk = 0;
rst = 1;
#timecycle rst = ~rst;
#timecycle rst = ~rst;
end
always #(timecycle/2) clk = ~clk;
signal_light_top traffic_tb(
.clk(clk),
.rst(rst),
.light1(light1),
.light2(light2),
.count(count)
);
endmodule
仿真结果:
参考: https://blog.csdn.net/xunzhaotadeyingzi/article/details/80052902