状态说明:
1, 初始化 东西南北的灯全亮;
2, 东西绿灯亮,南北红灯亮 20秒;
3, 东西黄灯亮,南北红灯亮 5秒;
4, 东西红灯亮,南北绿灯亮 20秒;
5, 东西红灯亮,南北黄灯亮 5秒;
6, 循环 2,3,4,5,
代码如下:
`timescale 1ns/1ps
//红黄绿
//1亮0灭
module traffic (
clk,
rst_n,
dongxi,
nanbei
);
input clk;
input rst_n;
output [2:0] dongxi;
output [2:0] nanbei;
reg [2:0] dongxi;
reg [2:0] nanbei;
parameter start=4'b0000, //开始
first=4'b0001, //第1位
second=4'b0010,//第2位
third=4'b0011, //第3位
fourth=4'b0100, //第4位
fifth=4'b0101, //第5位
sixth=4'b0110, //第6位
seventh=4'b0111, //第7位
eighth=4'b1000; //第8位
reg [3:0] state;
reg [5:0] cnt;
always @ (posedge clk or negedge rst_n)
begin
if(!rst_n) begin
dongxi <= 0;
nanbei <= 0;
cnt <= 0;
state <= start;
end
else
begin
case (state)
start: begin // chu shi
dongxi <= 3'b111;
nanbei <= 3'b111;
state <= first;
end
first: // dongxi lv 20s
if(cnt==20) begin
state <= second;
cnt <= 0;
end
else begin
cnt <= cnt + 1'b1;
dongxi <= 3'b001;
nanbei <= 3'b100;
state <= first;
end
second: // dongxi huang 5s
if(cnt==5) begin
state <= third;
cnt <= 0;
end
else begin
cnt <= cnt + 1'b1;
dongxi <= 3'b010;
nanbei <= 3'b100;
state <= second;
end
third: // nanbei lv 20s
if(cnt==20) begin
state <= fourth;
cnt <= 0;
end
else begin
cnt <= cnt + 1'b1;
dongxi <= 3'b100;
nanbei <= 3'b001;
state <= third;
end
fourth: // nanbei huang 5s
if(cnt==5) begin
state <= first;
cnt <= 0;
end
else begin
cnt <= cnt + 1'b1;
dongxi <= 3'b100;
nanbei <= 3'b010;
state <= fourth;
end
endcase
end
end
endmodule
测试激励:
`timescale 1ns/1ps
//
//
//
module traffic_tb;
reg clk;
reg rst_n;
wire dongxi;
wire nanbei;
traffic i1 (
.clk(clk),
.rst_n(rst_n),
.dongxi(dongxi),
.nanbei(nanbei)
);
parameter period = 10;
initial
begin
forever #(period/2) clk = ~clk;
end
initial
begin
clk = 0;
rst_n = 0;
#20 rst_n = 1;
#100000
$stop;
end
endmodule
|